diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 2d3a38168c79e..58771c8f07cc7 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -212,7 +212,7 @@ jobs: uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: native/resource-monitor/target/${{ inputs.rust_target }}/release/t3-resource-monitor${{ inputs.platform == 'win' && '.exe' || '' }} - key: resource-monitor-${{ inputs.rust_target }}-${{ hashFiles('.cargo/config.toml', 'native/resource-monitor/Cargo.lock', 'native/resource-monitor/Cargo.toml', 'native/resource-monitor/src/**') }} + key: resource-monitor-${{ inputs.rust_target }}-${{ hashFiles('.cargo/config.toml', 'native/resource-monitor/Cargo.lock', 'native/resource-monitor/Cargo.toml', 'native/resource-monitor/build.rs', 'native/resource-monitor/src/**') }} - name: Cache Linux capture helpers if: inputs.platform == 'linux' @@ -281,6 +281,15 @@ jobs: name: js-bundle path: apps + - name: Restore web asset manifest + shell: bash + run: | + client=apps/server/dist/client + if [[ -f "$client/vite-manifest.release.json" ]]; then + mkdir -p "$client/.vite" + mv "$client/vite-manifest.release.json" "$client/.vite/manifest.json" + fi + - name: Install cargo-xwin if: inputs.platform == 'win' && steps.resource_monitor_cache.outputs.cache-hit != 'true' uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6fe82ebcb0069..7caf4aeb2882e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -601,6 +601,15 @@ jobs: T3CODE_TELEMETRY_CHANNEL: ${{ github.repository == 'pingdotgg/t3code' && needs.preflight.outputs.release_channel || 'dev' }} run: vp run ${{ steps.bundle_build.outputs.script }} + # Upload only the expected hidden file, without opting all build outputs into hidden uploads. + - name: Stage web asset manifest + shell: bash + run: | + manifest=apps/server/dist/client/.vite/manifest.json + if [[ -f "$manifest" ]]; then + cp "$manifest" apps/server/dist/client/vite-manifest.release.json + fi + # Two paths under apps/ so the artifact root is apps/; consumers download # into `apps` to restore both at their original locations. - name: Upload JS bundle diff --git a/apps/desktop/package.json b/apps/desktop/package.json index bd770e285e71b..92a67f29471e2 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.1.11", + "version": "0.1.12", "private": true, "type": "module", "main": "dist-electron/boot.cjs", diff --git a/apps/desktop/src/app/DesktopEnvironment.ts b/apps/desktop/src/app/DesktopEnvironment.ts index d5fed4b228b6f..d012b5afe6f34 100644 --- a/apps/desktop/src/app/DesktopEnvironment.ts +++ b/apps/desktop/src/app/DesktopEnvironment.ts @@ -59,6 +59,7 @@ export class DesktopEnvironment extends Context.Service< readonly clientAssetsDir: string; readonly backendCwd: string; readonly preloadPath: string; + readonly previewPickPreloadPath: string; readonly compileCachePath: string; readonly appUpdateYmlPath: string; readonly devServerUrl: Option.Option; @@ -211,6 +212,7 @@ const make = Effect.fn("desktop.environment.make")(function* ( clientAssetsDir: path.join(serverRoot, "apps/server/dist/client"), backendCwd: input.isPackaged ? homeDirectory : appRoot, preloadPath: path.join(input.dirname, "preload.cjs"), + previewPickPreloadPath: path.join(input.dirname, "preview-pick-preload.cjs"), compileCachePath: path.join(input.dirname, "compileCache.cjs"), appUpdateYmlPath: input.isPackaged ? path.join(resourcesPath, "app-update.yml") diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index 9dc0465c1e55a..cb84223b73a07 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -39,6 +39,7 @@ import * as Schema from "effect/Schema"; import * as Option from "effect/Option"; import * as NodeURL from "node:url"; +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as BrowserImport from "../../preview/BrowserImport/BrowserImport.ts"; import * as LoopbackTunnel from "../../preview/LoopbackTunnel.ts"; @@ -363,6 +364,7 @@ const getPreviewConfig = DesktopIpc.makeIpcMethod({ }) { const manager = yield* PreviewManager.PreviewManager; const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + const environment = yield* DesktopEnvironment.DesktopEnvironment; const { scope, persistent, namespace } = resolvePartitionScope(environmentId, profileId); // Session creation installs UA and permission handlers before a guest can attach. const session = yield* manager.getBrowserSession(scope, persistent, namespace); @@ -371,7 +373,7 @@ const getPreviewConfig = DesktopIpc.makeIpcMethod({ return { partition: yield* manager.getBrowserPartition(scope, persistent, namespace), webPreferences: PREVIEW_WEBVIEW_PREFERENCES, - preloadUrl: NodeURL.pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href, + preloadUrl: NodeURL.pathToFileURL(environment.previewPickPreloadPath).href, }; }), }); diff --git a/apps/desktop/src/preview/PickPreload.test.ts b/apps/desktop/src/preview/PickPreload.test.ts index d250d726e43e0..527f770fcdfdc 100644 --- a/apps/desktop/src/preview/PickPreload.test.ts +++ b/apps/desktop/src/preview/PickPreload.test.ts @@ -1,3 +1,4 @@ +import type { PreviewAnnotationPayload } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; import { ELEMENT_PICKED_CHANNEL, START_PICK_CHANNEL } from "./GuestProtocol.ts"; @@ -46,6 +47,33 @@ const startAnnotation = (): ShadowRoot => { return shadowRoot; }; +const pickAndAttach = async (element: Element) => { + ipcSend.calls.length = 0; + document.elementsFromPoint = () => [element]; + using listeners = vi.spyOn(HTMLButtonElement.prototype, "addEventListener"); + const shadowRoot = startAnnotation(); + element.dispatchEvent( + new PointerEvent("pointerdown", { button: 0, clientX: 100, clientY: 100, bubbles: true }), + ); + const attach = Array.from(shadowRoot.querySelectorAll("button")).find( + (button) => button.textContent === "Attach", + ); + const listenerIndex = listeners.mock.contexts.findIndex( + (target, index) => target === attach && listeners.mock.calls[index]?.[0] === "click", + ); + const listener = listeners.mock.calls[listenerIndex]?.[1]; + if (!attach || typeof listener !== "function") throw new Error("Attach listener not found"); + // The DOM test environment has no native input source. + listener.call(attach, { isTrusted: true } as MouseEvent); + + await vi.waitFor(() => + expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(true), + ); + const [, annotation] = + ipcSend.calls.find(([channel]) => channel === ELEMENT_PICKED_CHANNEL) ?? []; + return (annotation as PreviewAnnotationPayload | undefined)?.elements[0]?.element; +}; + it("switches tools from the keyboard after a toolbar button is clicked", () => { const shadowRoot = startAnnotation(); const region = Array.from(shadowRoot.querySelectorAll("button")).find( @@ -168,7 +196,6 @@ it.each([ ); it("keeps only the well-typed fields of what the page reports about an element", async () => { - ipcSend.calls.length = 0; pageElementContext.mockResolvedValueOnce({ selector: { toString: () => "#object" }, htmlPreview: "", @@ -177,32 +204,9 @@ it("keeps only the well-typed fields of what the page reports about an element", stack: [{ functionName: "Checkout", fileName: ["x"], lineNumber: "12", columnNumber: 4 }, 3], }); const card = document.body.appendChild(document.createElement("div")); - document.elementsFromPoint = () => [card]; - using listeners = vi.spyOn(HTMLButtonElement.prototype, "addEventListener"); - const shadowRoot = startAnnotation(); - card.dispatchEvent( - new PointerEvent("pointerdown", { button: 0, clientX: 100, clientY: 100, bubbles: true }), - ); - const attach = Array.from(shadowRoot.querySelectorAll("button")).find( - (button) => button.textContent === "Attach", - ); - const listenerIndex = listeners.mock.contexts.findIndex( - (target, index) => target === attach && listeners.mock.calls[index]?.[0] === "click", - ); - const listener = listeners.mock.calls[listenerIndex]?.[1]; - if (!attach || typeof listener !== "function") throw new Error("Attach listener not found"); - // The DOM test environment has no native input source. - listener.call(attach, { isTrusted: true } as MouseEvent); - - await vi.waitFor(() => - expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(true), - ); - const [, annotation] = - ipcSend.calls.find(([channel]) => channel === ELEMENT_PICKED_CHANNEL) ?? []; + const element = await pickAndAttach(card); const frame = { functionName: "Checkout", fileName: null, lineNumber: null, columnNumber: 4 }; - expect( - (annotation as { elements: Array<{ element: unknown }> }).elements[0]?.element, - ).toMatchObject({ + expect(element).toMatchObject({ selector: null, htmlPreview: "", componentName: null, @@ -211,3 +215,11 @@ it("keeps only the well-typed fields of what the page reports about an element", stack: [frame, { functionName: null, fileName: null, lineNumber: null, columnNumber: null }], }); }); + +it("drops a straddling surrogate pair when falling back to outerHTML preview", async () => { + pageElementContext.mockRejectedValueOnce(new Error("page lookup failed")); + const card = document.body.appendChild(document.createElement("div")); + card.textContent = `${"a".repeat(494)}🚀tail`; + expect(card.outerHTML.charCodeAt(499)).toBe(0xd83d); + expect((await pickAndAttach(card))?.htmlPreview).toBe(card.outerHTML.slice(0, 499)); +}); diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index a227d5136b6c6..61e3c8070d722 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -494,10 +494,14 @@ async function captureElement(element: Element): Promise { }; } } catch {} + const html = element.outerHTML; + const before = html.charCodeAt(HTML_PREVIEW_MAX_CHARS - 1); + const after = html.charCodeAt(HTML_PREVIEW_MAX_CHARS); + const splitPair = before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff; return { ...base, selector: null, - htmlPreview: element.outerHTML.slice(0, HTML_PREVIEW_MAX_CHARS), + htmlPreview: html.slice(0, splitPair ? HTML_PREVIEW_MAX_CHARS - 1 : HTML_PREVIEW_MAX_CHARS), componentName: null, source: null, stack: [], diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index 657cdac1f59df..393c1f932f8c1 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -1390,6 +1390,15 @@ describe("describeUpdateErrorCause", () => { cyclic.cause = cyclic; assert.include(DesktopUpdates.describeUpdateErrorCause(cyclic), "[truncated cause]"); assert.isAtMost(DesktopUpdates.describeUpdateErrorCause(cyclic).length, 1024); + + const describeCause = (outer: string, inner: string) => + DesktopUpdates.describeUpdateErrorCause( + Object.assign(new Error(outer), { cause: new Error(inner) }), + ); + const a = "a".repeat(512); + const b = "b".repeat(485); + assert.equal(describeCause(`${a.slice(1)}🚀`, "b"), `Error: ${a.slice(1)}; caused by Error: b`); + assert.equal(describeCause(a, `${b}🚀`), `Error: ${a}; caused by Error: ${b}`); }); it("does not serialize arbitrary payloads or let unreadable errors break logging", () => { diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 06300354354d6..3fab1f9dad826 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -244,7 +244,8 @@ function redactMessage(message: string): string { /\b[\w-]*(?:token|password|secret|credential|api[_-]?key)[\w-]*\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi, "[redacted credential]", ) - .slice(0, 512); + .slice(0, 512) + .replace(/\p{Surrogate}$/u, ""); } function summarizeCause(cause: unknown, depth: number): string { @@ -281,7 +282,9 @@ function summarizeCause(cause: unknown, depth: number): string { export function describeUpdateErrorCause(cause: unknown): string { try { - return summarizeCause(cause, 0).slice(0, 1024); + return summarizeCause(cause, 0) + .slice(0, 1024) + .replace(/\p{Surrogate}$/u, ""); } catch { return "UnknownError"; } diff --git a/apps/desktop/src/updates/releaseNotes.test.ts b/apps/desktop/src/updates/releaseNotes.test.ts index a8fcc70ea355c..f1c5ffd07dc3f 100644 --- a/apps/desktop/src/updates/releaseNotes.test.ts +++ b/apps/desktop/src/updates/releaseNotes.test.ts @@ -299,4 +299,16 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { omittedReleaseCount: 0, }); }); + + it("does not split a surrogate pair when truncating a long item", () => { + const result = normalizeDesktopUpdateReleaseNotes( + `- ${"a".repeat(215)} 🚀 trailing text`, + "1.2.3", + "latest", + ); + + const item = result.releaseNotes[0]?.items[0]; + expect(item).toBe(`${"a".repeat(215)}...`); + expect(item?.isWellFormed()).toBe(true); + }); }); diff --git a/apps/desktop/src/updates/releaseNotes.ts b/apps/desktop/src/updates/releaseNotes.ts index 30bfb9ace64b8..bf874062b7d7e 100644 --- a/apps/desktop/src/updates/releaseNotes.ts +++ b/apps/desktop/src/updates/releaseNotes.ts @@ -70,7 +70,10 @@ function stripMarkup(input: string, keepBold = false): string { function truncateReleaseNoteItem(item: string): string { if (item.length <= MAX_RELEASE_NOTE_ITEM_LENGTH) return item; - return `${item.slice(0, MAX_RELEASE_NOTE_ITEM_LENGTH - 3).trimEnd()}...`; + return `${item + .slice(0, MAX_RELEASE_NOTE_ITEM_LENGTH - 3) + .replace(/\p{Surrogate}$/u, "") + .trimEnd()}...`; } function normalizeReleaseNoteLine(line: string): string { diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index d9d9d23646653..6da2c7b72d8f9 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -1558,13 +1558,17 @@ describe("DesktopWindow", () => { if (!willAttachWebview) { return yield* Effect.die("will-attach-webview listener was not registered"); } - const webPreferences: Electron.WebPreferences = {}; + const webPreferences: Electron.WebPreferences = { preload: "/repo/elsewhere/other.cjs" }; willAttachWebview({ preventDefault: () => {} }, webPreferences, { partition: "persist:t3code-preview-test", }); assert.deepEqual(webPreferences.additionalArguments, expected); assert.isTrue(webPreferences.contextIsolation); + assert.equal( + webPreferences.preload, + "/repo/apps/desktop/dist-electron/preview-pick-preload.cjs", + ); }).pipe(Effect.provide(layer)); }), ); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 2b2401f42d57a..0b635528a3cbe 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -641,6 +641,8 @@ export const make = Effect.gen(function* () { event.preventDefault(); return; } + // The guest always runs the app's own preload, whatever the element asked for. + webPreferences.preload = environment.previewPickPreloadPath; webPreferences.sandbox = true; webPreferences.nodeIntegration = false; webPreferences.nodeIntegrationInSubFrames = false; diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index 470091f334fb7..aab0f0b2f8eea 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -557,6 +557,7 @@ describe("parseResolvedPath", () => { const WSL_EXE = "/windows/System32/wsl.exe"; const STORE_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService"; const INBOX_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager"; +const SERVICES_ROOT = "HKLM\\SYSTEM\\CurrentControlSet\\Services"; const registrySpawner = (keys: ReadonlyArray) => ChildProcessSpawner.make((command) => @@ -570,7 +571,7 @@ const registrySpawner = (keys: ReadonlyArray) => ChildProcessSpawner.ExitCode( command._tag === "StandardCommand" && command.command === "reg.exe" && - keys.some((key) => command.args.includes(key)) + [SERVICES_ROOT, ...keys].some((key) => command.args.includes(key)) ? 0 : 1, ), @@ -608,6 +609,42 @@ describe("makeIsAvailable", () => { }), ); + it.effect("keeps WSL when registry tools are disabled by policy and reg.exe cannot answer", () => + Effect.gen(function* () { + const denied = new TextEncoder().encode( + "ERROR: Registry editing has been disabled by your administrator.\r\n", + ); + const blockedRegistry = ChildProcessSpawner.make(() => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + stdout: Stream.empty, + stderr: Stream.make(denied), + all: Stream.make(denied), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ), + ); + const available = yield* makeIsAvailable("win32", "/windows").pipe( + Effect.provide( + Layer.mergeAll( + FileSystem.layerNoop({ exists: (path) => Effect.succeed(path === WSL_EXE) }), + Path.layer, + DesktopManagedPolicy.layerTest(undefined), + ), + ), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, blockedRegistry), + ); + assert.isTrue(available); + }), + ); + it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () => Effect.gen(function* () { assert.isTrue(yield* isAvailable()); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index 9d9540a65dc7d..afd9ef013299d 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -1124,13 +1124,16 @@ const WSL_SERVICE_KEYS = [ "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService", "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager", ] as const; +// Always present; when reg.exe cannot read it (e.g. "Prevent access to registry editing tools"), +// a failed service query says nothing about WSL, so fall back to trusting wsl.exe. +const SERVICES_ROOT_KEY = "HKLM\\SYSTEM\\CurrentControlSet\\Services"; const SERVICE_QUERY_TIMEOUT = Duration.seconds(5); const wslServiceRegistered = Effect.scoped( Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const registered = yield* Effect.forEach( - WSL_SERVICE_KEYS, + const [rootReadable, ...servicesFound] = yield* Effect.forEach( + [SERVICES_ROOT_KEY, ...WSL_SERVICE_KEYS], (key) => spawner .spawn( @@ -1142,10 +1145,13 @@ const wslServiceRegistered = Effect.scoped( forceKillAfter: PROCESS_TERMINATE_GRACE, }), ) - .pipe(Effect.flatMap((handle) => handle.exitCode)), + .pipe( + Effect.flatMap((handle) => handle.exitCode), + Effect.map((exitCode) => (exitCode as unknown as number) === 0), + ), { concurrency: "unbounded" }, ); - return registered.some((exitCode) => (exitCode as unknown as number) === 0); + return rootReadable === false || servicesFound.includes(true); }), ).pipe( Effect.timeoutOption(SERVICE_QUERY_TIMEOUT), diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index a868851d5c9da..2a9fcfe5d7be8 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -183,6 +183,8 @@ const widgetsPlugin: NonNullable[number] = [ android: { minWidth: 250, minHeight: 180, + minResizeWidth: 180, + minResizeHeight: 130, targetCellWidth: 4, targetCellHeight: 3, resizeMode: "both", @@ -237,7 +239,7 @@ const config: ExpoConfig = { slug: "t3-code", platforms: ["ios", "android"], scheme: variant.scheme, - version: repoEnv.T3CODE_MOBILE_VERSION ?? "2.3.0", + version: repoEnv.T3CODE_MOBILE_VERSION ?? "2.4.0", runtimeVersion: { // Skip costly fingerprinting on dev launches; preview and production OTAs require matching native projects. policy: runtimeVersionPolicy, diff --git a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-3757a449.tgz b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-3757a449.tgz new file mode 100644 index 0000000000000..6ba7734e6509e Binary files /dev/null and b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-3757a449.tgz differ diff --git a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-a01cbf49.tgz b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-a01cbf49.tgz deleted file mode 100644 index 2b3b42ae4b7ad..0000000000000 Binary files a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-a01cbf49.tgz and /dev/null differ diff --git a/apps/mobile/index.ts b/apps/mobile/index.ts index 6717c79f2f87a..02ad9f496aa1f 100644 --- a/apps/mobile/index.ts +++ b/apps/mobile/index.ts @@ -3,6 +3,7 @@ import "./src/features/development/render-counter-entry"; import "./src/features/development/behavior-probe-entry"; // Crash reporting loads preferences, which can load GT and capture Hermes's Intl constructors. import "./src/i18n/intl-polyfills"; +import "./src/features/files/text-decoder-polyfill"; // Record errors thrown while the rest of the app loads. import "./src/features/observability/observe"; import { registerRootComponent } from "expo"; diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt index 69d9ae623b27b..b0094acd75e9a 100644 --- a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt +++ b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt @@ -13,6 +13,10 @@ internal object T3ComposerClipboard { fun hasThreadLink(text: String): Boolean = text.contains("t3-thread://v2/") || text.contains("https://app.t3.codes/threads/") + // Clipboard bridges can echo our text back without its HTML context metadata. + private var copiedContext: Pair? = null + + @Synchronized fun write(context: Context, text: String, fragment: String) { val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val payload = try { @@ -22,6 +26,7 @@ internal object T3ComposerClipboard { } val records = payload?.optJSONArray("records") if (payload == null || records == null) { + copiedContext = null clipboard.setPrimaryClip(ClipData.newPlainText("T3 Code", text)) return } @@ -35,8 +40,10 @@ internal object T3ComposerClipboard { } ) payload.put("records", JSONArray(selected)) - val encoded = java.net.URLEncoder.encode(payload.toString(), "UTF-8").replace("+", "%20") + val serialized = payload.toString() + val encoded = java.net.URLEncoder.encode(serialized, "UTF-8").replace("+", "%20") val escaped = text.replace("&", "&").replace("<", "<").replace(">", ">") + copiedContext = if (selected.isEmpty()) null else text to serialized clipboard.setPrimaryClip( if (selected.isEmpty()) { ClipData.newPlainText( @@ -53,14 +60,22 @@ internal object T3ComposerClipboard { ) } + @Synchronized fun read(context: Context): Map { val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = clipboard.primaryClip val item = if (clip != null && clip.itemCount > 0) clip.getItemAt(0) else null + val text = item?.text?.toString() ?: "" + val html = item?.htmlText ?: "" + val copied = copiedContext?.takeIf { + clip?.itemCount == 1 && item?.uri == null && it.first == text + } + if (copied == null) copiedContext = null return mapOf( - "text" to (item?.text?.toString() ?: ""), - "html" to (item?.htmlText ?: ""), - "fragment" to "" + "text" to text, + "html" to html, + "fragment" to + if (!html.contains("data-t3-context-fragment=")) copied?.second.orEmpty() else "" ) } } diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt index 52c69e3c3be49..6f90e2e12fa4e 100644 --- a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt +++ b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt @@ -906,7 +906,8 @@ internal class SelectionAwareEditText( private fun pasteContextOrImages(): Boolean { val payload = T3ComposerClipboard.read(context) return when { - payload["html"]?.contains("data-t3-context-fragment=") == true -> pasteContext(payload) + !payload["fragment"].isNullOrEmpty() || + payload["html"]?.contains("data-t3-context-fragment=") == true -> pasteContext(payload) pasteImagesOrInterceptedText() -> true isSingleItemClip() && T3ComposerClipboard.hasThreadLink(payload["text"].orEmpty()) -> pasteContext(payload) diff --git a/apps/mobile/modules/t3-composer-editor/android/src/test/java/expo/modules/t3composereditor/ComposerPasteTest.kt b/apps/mobile/modules/t3-composer-editor/android/src/test/java/expo/modules/t3composereditor/ComposerPasteTest.kt index bf6ee85877497..92d88072d6236 100644 --- a/apps/mobile/modules/t3-composer-editor/android/src/test/java/expo/modules/t3composereditor/ComposerPasteTest.kt +++ b/apps/mobile/modules/t3-composer-editor/android/src/test/java/expo/modules/t3composereditor/ComposerPasteTest.kt @@ -15,6 +15,7 @@ import android.view.View import android.view.KeyEvent import android.view.inputmethod.BaseInputConnection import android.view.inputmethod.EditorInfo +import org.json.JSONObject import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull @@ -50,6 +51,46 @@ class ComposerPasteTest { ) ) + @Test + @Config(sdk = [33, 36]) + fun sentImageCopySurvivesAClipboardBridgeDroppingHtml() { + val id = "file_sent-image" + val copiedText = "Review this image\n ![android-smoke.png](t3-context://v1/image/$id)" + val fragment = """ + { + "version": 1, + "source": {"environmentId": "source", "messageId": "sent-message"}, + "records": [{ + "version": 1, "contextId": "$id", "label": "android-smoke.png", "kind": "image", + "attachmentId": "stored-image", "name": "android-smoke.png", + "mimeType": "image/png", "sizeBytes": 53249 + }] + } + """.trimIndent() + T3ComposerClipboard.write(context, copiedText, fragment) + clipboard.setPrimaryClip(ClipData.newPlainText("clipboard bridge", copiedText)) + editor.setText("") + editor.setSelection(0) + var pasted: Map? = null + editor.pasteContextListener = { pasted = it } + + assertTrue(editor.onTextContextMenuItem(android.R.id.paste)) + assertEquals(copiedText, pasted?.get("text")) + val recovered = JSONObject(requireNotNull(pasted?.get("fragment"))) + assertEquals("source", recovered.getJSONObject("source").getString("environmentId")) + assertEquals(id, recovered.getJSONArray("records").getJSONObject(0).getString("contextId")) + assertEquals("", editor.text.toString()) + + editor.pasteContextListener = { error("Paste as Text must stay plain") } + assertTrue(pasteAsText()) + assertEquals(copiedText, editor.text.toString()) + + clipboard.setPrimaryClip(ClipData.newPlainText("other app", "Different text")) + assertEquals("", T3ComposerClipboard.read(context)["fragment"]) + clipboard.setPrimaryClip(ClipData.newPlainText("other app", copiedText)) + assertEquals("", T3ComposerClipboard.read(context)["fragment"]) + } + @Test fun shortcutKeepsLargeTextInlineAndUndoable() { val pasted = "x".repeat(32 * 1024) diff --git a/apps/mobile/modules/t3-voice-transcription/android/src/main/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriber.kt b/apps/mobile/modules/t3-voice-transcription/android/src/main/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriber.kt index ce722817dd131..1e2e726ccf650 100644 --- a/apps/mobile/modules/t3-voice-transcription/android/src/main/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriber.kt +++ b/apps/mobile/modules/t3-voice-transcription/android/src/main/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriber.kt @@ -24,7 +24,13 @@ internal class VoiceTranscriptionException( // ML Kit reports every mode UNAVAILABLE for tags with Unicode extensions, which Android adds // for regional preferences such as the temperature unit (en-US-u-mu-celsius). -internal fun speechLocale(systemLocale: Locale): Locale = systemLocale.stripExtensions() +internal fun speechLocale(systemLocale: Locale): Locale { + val locale = systemLocale.stripExtensions() + // ML Kit accepts cmn-Hans-CN for Simplified Chinese, not zh-CN or zh-Hans-CN. + val simplifiedChinese = locale.language == "zh" && + (locale.script == "Hans" || (locale.script.isEmpty() && locale.country == "CN")) + return if (simplifiedChinese) Locale.forLanguageTag("cmn-Hans-CN") else locale +} private val recognitionModes = listOf( SpeechRecognizerOptions.Mode.MODE_ADVANCED, diff --git a/apps/mobile/modules/t3-voice-transcription/android/src/test/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriberTest.kt b/apps/mobile/modules/t3-voice-transcription/android/src/test/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriberTest.kt index 445411bbb6957..e1eb1be2d5f0f 100644 --- a/apps/mobile/modules/t3-voice-transcription/android/src/test/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriberTest.kt +++ b/apps/mobile/modules/t3-voice-transcription/android/src/test/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriberTest.kt @@ -21,6 +21,9 @@ class GoogleVoiceTranscriberTest { "en-US-u-mu-celsius" to "en-US", "en-GB-u-fw-mon-mu-celsius" to "en-GB", "ar-EG-u-nu-latn" to "ar-EG", + "zh-CN" to "cmn-Hans-CN", + "zh-Hans-CN" to "cmn-Hans-CN", + "zh-Hans-CN-u-fw-mon" to "cmn-Hans-CN", "zh-Hant-TW" to "zh-Hant-TW" )) { assertEquals(expected, speechLocale(Locale.forLanguageTag(system)).toLanguageTag()) diff --git a/apps/mobile/package.json b/apps/mobile/package.json index c7342ef775668..8bef7492c5b0f 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -45,7 +45,6 @@ "sync:chip-icons": "node scripts/sync-context-chip-icons.mjs", "sync:link-icons": "node scripts/sync-link-icons.ts", "sync:pierre-icons": "node scripts/sync-pierre-file-icons.mjs", - "measure-renders": "node scripts/measure-renders.mts", "generate": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON scripts/generate-uniwind-themes.mts", "generate:highlights": "node scripts/generate-highlights.mts", "generate:nitro": "cd modules/t3-highlights && nitrogen", @@ -57,6 +56,7 @@ "@clerk/expo": "catalog:", "@clerk/expo-native-components": "0.4.8", "@effect/atom-react": "catalog:", + "@exodus/bytes": "1.15.1", "@expo-google-fonts/dm-sans": "^0.4.2", "@expo/metro-runtime": "~58.0.17", "@expo/ui": "58.0.29", @@ -126,7 +126,7 @@ "react": "catalog:", "react-dom": "catalog:", "react-native": "0.88.1", - "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.19-a01cbf49.tgz", + "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.19-3757a449.tgz", "react-native-gesture-handler": "~3.5.0", "react-native-image-viewing": "^0.2.2", "react-native-keyboard-controller": "1.23.0", @@ -146,7 +146,6 @@ }, "devDependencies": { "@babel/core": "^7.29.7", - "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", "@pierre/trees": "catalog:", "@types/mdast": "^4.0.4", diff --git a/apps/mobile/scripts/measure-renders.mts b/apps/mobile/scripts/measure-renders.mts deleted file mode 100644 index a49d1ee170f67..0000000000000 --- a/apps/mobile/scripts/measure-renders.mts +++ /dev/null @@ -1,408 +0,0 @@ -// See docs/internals/13_mobile-development.md#measuring-renders. -import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"; -import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; -import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as NodeWS from "@effect/platform-node/NodeWS"; -import { - CommandId, - EnvironmentId, - ExecutionEnvironmentDescriptor, - ORCHESTRATION_PROTOCOL_HEADER, - ORCHESTRATION_PROTOCOL_VERSION, - OrchestrationV2ShellSnapshot, - ProjectId, - ProviderInstanceId, - ThreadId, - WsRpcGroup, - type OrchestrationV2ThreadProjection, -} from "@t3tools/contracts"; -import * as Console from "effect/Console"; -import * as SecureRandom from "effect/crypto/SecureRandom"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; -import { Command, Flag } from "effect/cli"; -import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; -import { RpcClient, RpcSerialization } from "effect/rpc"; -import { Socket } from "effect/socket"; - -const RenderReport = Schema.Struct({ - commits: Schema.Number, - totalRenders: Schema.Number, - components: Schema.Array(Schema.Struct({ key: Schema.String, count: Schema.Number })), - causes: Schema.Array(Schema.Struct({ key: Schema.String, count: Schema.Number })), -}); -type RenderReport = typeof RenderReport.Type; -const decodeReport = Schema.decodeUnknownEffect(Schema.fromJsonString(RenderReport)); -const InspectorTargets = Schema.Array( - Schema.Struct({ appId: Schema.String, webSocketDebuggerUrl: Schema.String }), -); -const CdpReply = Schema.Struct({ - id: Schema.Number, - result: Schema.optional( - Schema.Struct({ - result: Schema.optional(Schema.Struct({ value: Schema.optional(Schema.Unknown) })), - exceptionDetails: Schema.optional(Schema.Unknown), - }), - ), -}); -const decodeCdpReply = Schema.decodeUnknownOption(Schema.fromJsonString(CdpReply)); -const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); - -class MeasureError extends Schema.TaggedError()("MeasureError", { - message: Schema.String, -}) {} - -const STREAM_PROMPT = - "Think it through step by step, then write a 3000-word essay on the history of typesetting in plain paragraphs with a few headings. Do not use any tools."; - -interface Options { - readonly server: string; - readonly token: string; - readonly metro: string; - readonly scheme: string; - readonly runs: number; - readonly windowSeconds: number; - readonly provider: string; - readonly model: string; - readonly projectRoot: string; -} - -const uuid = Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4()); - -const median = (values: ReadonlyArray) => { - const sorted = [...values].sort((a, b) => a - b); - const middle = Math.floor(sorted.length / 2); - return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2; -}; - -const connectInspector = Effect.fn("measure.connectInspector")(function* (metro: string) { - const http = yield* HttpClient.HttpClient; - const targets = yield* http - .get(`${metro}/json/list`) - .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(InspectorTargets))); - const target = targets.find((entry) => entry.appId.startsWith("com.t3tools.t3code")); - if (!target) - return yield* new MeasureError({ message: `No T3 Code app is attached to Metro at ${metro}.` }); - // Expo closes inspector sockets unless Origin matches Metro's advertised URL; pass that URL as --metro. - const socket = yield* Socket.makeWebSocket(target.webSocketDebuggerUrl, { - headers: { origin: new URL(metro).origin }, - openTimeout: "10 seconds", - }); - const writer = yield* socket.writer; - const reader = yield* socket.reader; - let nextId = 0; - return Effect.fn("measure.evaluate")(function* (expression: string) { - const id = ++nextId; - yield* writer.write( - encodeJson({ id, method: "Runtime.evaluate", params: { expression, returnByValue: true } }), - ); - while (true) { - for (const frame of yield* reader.pull) { - const text = typeof frame === "string" ? frame : new TextDecoder().decode(frame); - const reply = decodeCdpReply(text); - if (Option.isNone(reply) || reply.value.id !== id) continue; - if (reply.value.result?.exceptionDetails) - return yield* new MeasureError({ - message: `Evaluation failed: ${encodeJson(reply.value.result.exceptionDetails)}`, - }); - return reply.value.result?.result?.value; - } - } - }); -}); - -const connectServer = Effect.fn("measure.connectServer")(function* (options: Options) { - const http = (yield* HttpClient.HttpClient).pipe( - HttpClient.mapRequest((request) => - request.pipe( - HttpClientRequest.bearerToken(options.token), - HttpClientRequest.setHeader( - ORCHESTRATION_PROTOCOL_HEADER, - String(ORCHESTRATION_PROTOCOL_VERSION), - ), - ), - ), - HttpClient.filterStatusOk, - ); - const descriptor = yield* http - .get(`${options.server}/.well-known/t3/environment`) - .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor))); - const shell = yield* http - .get(`${options.server}/api/orchestration/shell`) - .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(OrchestrationV2ShellSnapshot))); - let projectId = shell.projects.find( - (project) => project.workspaceRoot === options.projectRoot, - )?.id; - // A project record outlives its folder, and turns fail without it. - yield* (yield* FileSystem.FileSystem).makeDirectory(options.projectRoot, { recursive: true }); - if (!projectId) { - projectId = ProjectId.make(yield* uuid); - yield* http.execute( - HttpClientRequest.post(`${options.server}/api/projects/mutate`).pipe( - HttpClientRequest.bodyJsonUnsafe({ - type: "project.create", - commandId: yield* uuid, - projectId, - title: "Render measurement", - workspaceRoot: options.projectRoot, - }), - ), - ); - } - const ticket = yield* http - .execute(HttpClientRequest.post(`${options.server}/api/auth/websocket-ticket`)) - .pipe( - Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), - ); - // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns. - const protocol = yield* Layer.build( - RpcClient.layerProtocolSocket().pipe( - Layer.provide( - Socket.layerWebSocket( - `${options.server.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket.ticket)}`, - ), - ), - Layer.provide(RpcSerialization.layerJson), - ), - ); - const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); - return { client, environmentId: EnvironmentId.make(descriptor.environmentId), projectId }; -}); - -// Some providers stream only reasoning, so any streaming text item counts. -const streamingItem = (projection: OrchestrationV2ThreadProjection) => - projection.turnItems.find( - (item) => (item.type === "assistant_message" || item.type === "reasoning") && item.streaming, - ); - -const measureStreamReply = Effect.fn("measure.streamReply")(function* ( - options: Options, - run: number, - route: Option.Option, -) { - if (Option.isSome(route)) yield* reloadAndOpen(options, route.value); - const evaluate = yield* connectInspector(options.metro); - const { client, environmentId, projectId } = yield* connectServer(options); - const threadId = ThreadId.make(yield* uuid); - yield* client["orchestration.launchThread"]({ - commandId: CommandId.make(yield* uuid), - threadId, - projectId, - title: `Render measurement ${run}`, - modelSelection: { - instanceId: ProviderInstanceId.make(options.provider), - model: options.model, - }, - // The prompt needs no tools; approval-required keeps a stray call from acting. - runtimeMode: "approval-required", - interactionMode: "default", - workspaceStrategy: { type: "root" }, - initialMessage: { text: STREAM_PROMPT, attachments: [] }, - }); - // A failed or interrupted window must not leave a provider turn running. - yield* Effect.addFinalizer(() => - Effect.gen(function* () { - const after = yield* client["orchestration.getThreadProjection"]({ threadId }); - const activeRun = after.runs.find( - (entry) => !["completed", "failed", "interrupted", "cancelled"].includes(entry.status), - ); - if (!activeRun) return; - yield* client["orchestration.dispatchCommand"]({ - type: "run.interrupt", - commandId: CommandId.make(yield* uuid), - threadId, - runId: activeRun.id, - }); - }).pipe(Effect.ignore), - ); - if (Option.isNone(route)) - yield* evaluate( - `__t3RenderCounterOpen(${encodeJson(`${options.scheme}://threads/${environmentId}/${threadId}`)})`, - ); - const projectionOf = (item: { kind: string; projection?: OrchestrationV2ThreadProjection }) => - item.kind === "snapshot" && item.projection - ? Effect.succeed(item.projection) - : client["orchestration.getThreadProjection"]({ threadId }); - const streaming = yield* client["orchestration.subscribeThread"]({ threadId }).pipe( - Stream.mapEffect(projectionOf), - Stream.filter((projection) => streamingItem(projection) !== undefined), - Stream.runHead, - Effect.timeout("90 seconds"), - ); - if (Option.isNone(streaming)) - return yield* new MeasureError({ message: `Run ${run}: the reply never started streaming.` }); - yield* evaluate("__t3RenderCounterStart()"); - yield* Effect.sleep(`${options.windowSeconds} seconds`); - const report = yield* decodeReport(yield* evaluate("JSON.stringify(__t3RenderCounterStop())")); - // An in-view streaming thread must commit; out-of-view streaming may commit nothing. - if (report.commits === 0 && Option.isNone(route)) - return yield* new MeasureError({ - message: `Run ${run}: no React commits in the window. Check the device for a red box.`, - }); - const after = yield* client["orchestration.getThreadProjection"]({ threadId }); - return { report, stillStreaming: streamingItem(after) !== undefined }; -}, Effect.scoped); - -const appLink = (options: Options, route: string) => - `__t3RenderCounterOpen(${encodeJson(`${options.scheme}://${route.replace(/^\//, "")}`)})`; - -const reloadAndOpen = Effect.fn("measure.reloadAndOpen")(function* ( - options: Options, - route: string, -) { - // A link to an already-open screen only refocuses it, so each run starts from a reload. - yield* Effect.scoped( - Effect.flatMap(connectInspector(options.metro), (evaluate) => - evaluate("__t3RenderCounterReload()"), - ), - ); - yield* Effect.sleep("15 seconds"); - if (route === "/" || route === "") return; - yield* Effect.scoped( - Effect.flatMap(connectInspector(options.metro), (evaluate) => - evaluate(appLink(options, route)), - ), - ); - yield* Effect.sleep("5 seconds"); -}); - -const measureRouteOpen = Effect.fn("measure.routeOpen")(function* ( - options: Options, - route: string, - run: number, -) { - yield* Effect.scoped( - Effect.flatMap(connectInspector(options.metro), (evaluate) => - evaluate("__t3RenderCounterReload()"), - ), - ); - yield* Effect.sleep("15 seconds"); - const evaluate = yield* connectInspector(options.metro); - yield* evaluate("__t3RenderCounterStart()"); - yield* evaluate(appLink(options, route)); - yield* Effect.sleep(`${options.windowSeconds} seconds`); - const report = yield* decodeReport(yield* evaluate("JSON.stringify(__t3RenderCounterStop())")); - if (report.commits === 0) - return yield* new MeasureError({ - message: `Run ${run}: no React commits in the window. Check that ${route} is a valid app path.`, - }); - return { report, stillStreaming: undefined }; -}, Effect.scoped); - -const medianTable = ( - title: string, - reports: ReadonlyArray, - pick: (report: RenderReport) => RenderReport["causes"], - limit: number, -) => { - const keys = new Set(reports.flatMap((report) => pick(report).map((entry) => entry.key))); - const rows = [...keys] - .map((key) => ({ - key, - count: median(reports.map((report) => pick(report).find((e) => e.key === key)?.count ?? 0)), - })) - .filter((row) => row.count > 0) - .sort((a, b) => b.count - a.count) - .slice(0, limit); - return [ - `| ${title} | Renders |`, - "|---|---:|", - ...rows.map((r) => `| \`${r.key}\` | ${r.count} |`), - ]; -}; - -const formatTable = (reports: ReadonlyArray) => { - const totals = (pick: (report: RenderReport) => number) => median(reports.map(pick)); - return [ - `Median of ${reports.length} runs.`, - "", - "| | |", - "|---|---:|", - `| renders | ${totals((r) => r.totalRenders)} |`, - `| commits | ${totals((r) => r.commits)} |`, - // Provider pace sets how many commits land in the window; per-commit cost compares across runs. - `| renders per commit | ${totals((r) => Math.round(r.totalRenders / Math.max(r.commits, 1)))} |`, - "", - ...medianTable("Component", reports, (r) => r.components, 20), - "", - ...medianTable("Cause", reports, (r) => r.causes, 15), - ].join("\n"); -}; - -const command = Command.make( - "measure-renders", - { - server: Flag.String("server").pipe( - Flag.withDescription("T3 server origin the app is paired with."), - Flag.withDefault(""), - ), - token: Flag.String("token").pipe( - Flag.withDescription("Bearer token from `t3 auth session issue --token-only`."), - Flag.withDefault(""), - ), - route: Flag.String("route").pipe( - Flag.withDescription( - "App path to open and measure. With --server, the path stays open while a new thread streams.", - ), - Flag.optional, - ), - metro: Flag.String("metro").pipe(Flag.withDefault("http://127.0.0.1:8081")), - scheme: Flag.String("scheme").pipe(Flag.withDefault("t3code-dev")), - runs: Flag.Int("runs").pipe(Flag.withDefault(3)), - window: Flag.Int("window").pipe( - Flag.withDescription("Seconds to record; defaults to 12 for a reply and 6 for --route."), - Flag.optional, - ), - provider: Flag.String("provider").pipe(Flag.withDefault("claudeAgent")), - model: Flag.String("model").pipe(Flag.withDefault("claude-haiku-5-5")), - projectRoot: Flag.String("project-root").pipe( - Flag.withDescription("Scratch directory for the measurement project; created if missing."), - Flag.withDefault(""), - ), - }, - Effect.fn("measure.main")(function* (flags) { - const route = flags.route; - const options: Options = { - ...flags, - windowSeconds: Option.getOrElse(flags.window, () => - Option.isSome(route) && !flags.server ? 6 : 12, - ), - }; - const streams = Option.isNone(route) || flags.server !== ""; - if (streams && (!flags.server || !flags.token || !flags.projectRoot)) - return yield* new MeasureError({ - message: "Streaming a reply needs --server, --token and --project-root.", - }); - const reports: RenderReport[] = []; - for (let run = 1; run <= flags.runs; run++) { - const { report, stillStreaming } = - Option.isSome(route) && !streams - ? yield* measureRouteOpen(options, route.value, run) - : yield* measureStreamReply(options, run, route); - yield* Console.error( - `run ${run}: ${report.totalRenders} renders in ${report.commits} commits${stillStreaming === false ? " (warning: streaming ended inside the window)" : ""}`, - ); - reports.push(report); - // Let the interrupted turn settle so the next run starts from a quiet app. - yield* Effect.sleep("3 seconds"); - } - yield* Console.log(formatTable(reports)); - }), -); - -Command.run(command, { version: "0.0.0" }).pipe( - Effect.provide( - Layer.mergeAll( - NodeServices.layer, - NodeCrypto.layer, - NodeHttpClient.layerUndici, - NodeWS.layerWebSocketConstructor, - ), - ), - NodeRuntime.runMain, -); diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index 16a77b049efa3..7193fcb9b7af8 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -109,6 +109,7 @@ import { import { pruneNewTaskFlowStates } from "./features/threads/new-task-flow-state"; import { pruneNewTaskBranchCheckouts } from "./features/threads/NewTaskDraftRouteScreen"; import { installAppUpdateChecks } from "./features/updates/app-updates"; +import { perfProbe } from "./features/development/perf-probe-hooks"; import "../global.css"; @@ -303,7 +304,12 @@ function AppContent() { - + diff --git a/apps/mobile/src/components/RenderErrorBoundary.logic.test.ts b/apps/mobile/src/components/RenderErrorBoundary.logic.test.ts new file mode 100644 index 0000000000000..53ba274800c00 --- /dev/null +++ b/apps/mobile/src/components/RenderErrorBoundary.logic.test.ts @@ -0,0 +1,9 @@ +import { expect, it } from "vite-plus/test"; + +import { errorDetailsPreview } from "./RenderErrorBoundary.logic"; + +it("previews the first line up to 300 units without splitting an emoji", () => { + expect(errorDetailsPreview(`${"a".repeat(299)}😀 more`)).toBe("a".repeat(299)); + expect(errorDetailsPreview(`${"a".repeat(298)}😀 more`)).toBe(`${"a".repeat(298)}😀`); + expect(errorDetailsPreview("TypeError: boom 🚀\n at render")).toBe("TypeError: boom 🚀"); +}); diff --git a/apps/mobile/src/components/RenderErrorBoundary.logic.ts b/apps/mobile/src/components/RenderErrorBoundary.logic.ts new file mode 100644 index 0000000000000..635b6b5fdcaaf --- /dev/null +++ b/apps/mobile/src/components/RenderErrorBoundary.logic.ts @@ -0,0 +1,11 @@ +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; + +const PREVIEW_LIMIT = 300; + +export function errorDetailsPreview(details: string) { + const firstLine = details.split("\n", 1)[0] ?? ""; + return firstLine.slice( + 0, + splitsSurrogatePair(firstLine, PREVIEW_LIMIT) ? PREVIEW_LIMIT - 1 : PREVIEW_LIMIT, + ); +} diff --git a/apps/mobile/src/components/RenderErrorBoundary.tsx b/apps/mobile/src/components/RenderErrorBoundary.tsx index aea8cdc090466..cadb6a00b8a6a 100644 --- a/apps/mobile/src/components/RenderErrorBoundary.tsx +++ b/apps/mobile/src/components/RenderErrorBoundary.tsx @@ -6,6 +6,7 @@ import { ScrollView, View } from "react-native"; import { AppText as Text } from "./ui/AppText"; import { Button } from "./ui/Button"; import { copyTextWithHaptic } from "../lib/copyTextWithHaptic"; +import { errorDetailsPreview } from "./RenderErrorBoundary.logic"; interface RenderErrorBoundaryProps { readonly children: ReactNode; @@ -112,7 +113,7 @@ export function RenderFailureView( Try again. If it keeps happening, copy the details for a bug report. - {props.details.split("\n", 1)[0]?.slice(0, 300)} + {errorDetailsPreview(props.details)}