diff --git a/apps/desktop/src/ipc/methods/sshEnvironment.ts b/apps/desktop/src/ipc/methods/sshEnvironment.ts index 15e04f71282b1..b368b5581d06d 100644 --- a/apps/desktop/src/ipc/methods/sshEnvironment.ts +++ b/apps/desktop/src/ipc/methods/sshEnvironment.ts @@ -26,7 +26,6 @@ import { } from "@t3tools/contracts"; import { SshHttpBridgeError } from "@t3tools/ssh/errors"; import { resolveLoopbackSshHttpBaseUrl } from "@t3tools/ssh/tunnel"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -35,10 +34,12 @@ import * as DesktopIpc from "../DesktopIpc.ts"; import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts"; import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts"; -type DesktopSshEnvironmentRequestOperation = - | "fetch-environment-descriptor" - | "bootstrap-bearer-session" - | "fetch-session-state"; +const DesktopSshEnvironmentRequestOperation = Schema.Literals([ + "fetch-environment-descriptor", + "bootstrap-bearer-session", + "fetch-session-state", +]); +type DesktopSshEnvironmentRequestOperation = typeof DesktopSshEnvironmentRequestOperation.Type; type DesktopSshEnvironmentRequestCause = RemoteEnvironmentAuthError | SshHttpBridgeError; @@ -47,12 +48,13 @@ const isEnvironmentInternalError = Schema.is(EnvironmentInternalError); const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError); const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError); const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError); +const isRemoteEnvironmentAuthUndeclaredStatusError = Schema.is( + RemoteEnvironmentAuthUndeclaredStatusError, +); +const isSshHttpBridgeError = Schema.is(SshHttpBridgeError); function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null { - if ( - cause instanceof RemoteEnvironmentAuthUndeclaredStatusError || - cause instanceof SshHttpBridgeError - ) { + if (isRemoteEnvironmentAuthUndeclaredStatusError(cause) || isSshHttpBridgeError(cause)) { return cause.status ?? null; } if (isEnvironmentRequestInvalidError(cause)) { @@ -73,13 +75,14 @@ function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | n return null; } -export class DesktopSshEnvironmentRequestError extends Data.TaggedError( +export class DesktopSshEnvironmentRequestError extends Schema.TaggedError()( "DesktopSshEnvironmentRequestError", -)<{ - readonly operation: DesktopSshEnvironmentRequestOperation; - readonly cause: DesktopSshEnvironmentRequestCause; - readonly sshHttpStatus: number | null; -}> { + { + operation: DesktopSshEnvironmentRequestOperation, + cause: Schema.Defect(), + sshHttpStatus: Schema.NullOr(Schema.Number), + }, +) { // The web client matches "[ssh_http:500]" to explain version-skewed SSH pairing. override get message() { const prefix = this.sshHttpStatus === null ? "" : `[ssh_http:${this.sshHttpStatus}] `; diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts index 721f130ef5e56..59d658e1eedaf 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts @@ -1872,7 +1872,9 @@ it.effect("capture fails closed while snapshots are disabled", () => { it.effect("points capture setup failures at SnapShot settings", () => { vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - linuxCaptureMock.mockRejectedValueOnce(new CaptureSetupRequiredError("Install the helper.")); + linuxCaptureMock.mockRejectedValueOnce( + new CaptureSetupRequiredError({ state: "Install the helper." }), + ); return Effect.scoped( Effect.gen(function* () { const service = yield* DesktopSnapShot.make; diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.ts b/apps/desktop/src/snapShot/DesktopSnapShot.ts index ae0c2f04121ea..53799e1577939 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.ts @@ -94,6 +94,8 @@ import { import * as HostProcess from "@t3tools/shared/HostProcess"; import { readImageDimensions } from "@t3tools/shared/imageDimensions"; +const isCaptureSetupRequiredError = Schema.is(CaptureSetupRequiredError); + const MAX_CAPTURE_WIDTH = 2_560; const MAX_CAPTURE_HEIGHT = 1_600; const SHORTCUT_COOLDOWN_NS = 200_000_000n; @@ -180,7 +182,7 @@ const shortcutFailure = (cause: unknown) => new SnapShotShortcutError({ cause }) function captureFailure(cause: unknown, captureId?: string): DesktopSnapShotError { if (isDesktopSnapShotError(cause)) return cause; - const operation = cause instanceof CaptureSetupRequiredError ? "setup-required" : "capture"; + const operation = isCaptureSetupRequiredError(cause) ? "setup-required" : "capture"; return new DesktopSnapShotError({ operation, captureId, cause }); } diff --git a/apps/desktop/src/snapShot/HyprlandSnapShot.ts b/apps/desktop/src/snapShot/HyprlandSnapShot.ts index a0b8b4181cd2a..c40f397809d26 100644 --- a/apps/desktop/src/snapShot/HyprlandSnapShot.ts +++ b/apps/desktop/src/snapShot/HyprlandSnapShot.ts @@ -171,11 +171,11 @@ export async function captureHyprlandWindow( let state = await setup.state(); if (state.status === "update-required") { await setup.perform("install-hyprland-helper").catch((cause: unknown) => { - throw new CaptureSetupRequiredError(state.message, { cause }); + throw new CaptureSetupRequiredError({ state: state.message, cause }); }); state = await setup.state(); } - if (state.status !== "ready") throw new CaptureSetupRequiredError(state.message); + if (state.status !== "ready") throw new CaptureSetupRequiredError({ state: state.message }); const executable = hyprlandCaptureExecutable(paths); const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-hyprland-capture-")); const cleanup = () => NodeFSP.rm(directory, { recursive: true, force: true }); diff --git a/apps/desktop/src/snapShot/KdeSnapShot.ts b/apps/desktop/src/snapShot/KdeSnapShot.ts index 2e5723f51aae0..f141bd485d027 100644 --- a/apps/desktop/src/snapShot/KdeSnapShot.ts +++ b/apps/desktop/src/snapShot/KdeSnapShot.ts @@ -215,7 +215,7 @@ export async function captureKdeWindow( options?: { readonly flash: boolean; readonly animate: boolean }, ): Promise { const state = await new KdeCaptureSetup(paths).state(); - if (state.status !== "ready") throw new CaptureSetupRequiredError(state.message); + if (state.status !== "ready") throw new CaptureSetupRequiredError({ state: state.message }); const { executable } = kdeCapturePaths(paths); const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-kde-capture-")); let retained = false; diff --git a/apps/desktop/src/snapShot/linuxCaptureSession.ts b/apps/desktop/src/snapShot/linuxCaptureSession.ts index 11bf3984223df..e1f7c3601efc0 100644 --- a/apps/desktop/src/snapShot/linuxCaptureSession.ts +++ b/apps/desktop/src/snapShot/linuxCaptureSession.ts @@ -2,15 +2,19 @@ import * as NodeFSP from "node:fs/promises"; import * as NodeURL from "node:url"; import type { SnapShotKeyChord } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; import { nativeImage } from "electron"; // Keep dbus-next out of desktop detection and PNG reads in the main process. export const HYPRLAND_CAPTURE_ACTION = "capture-window"; -export class CaptureSetupRequiredError extends Error { - constructor(state: string, options?: ErrorOptions) { - super(`${state} Open Settings → SnapShots to continue setup.`, options); +export class CaptureSetupRequiredError extends Schema.TaggedError()( + "CaptureSetupRequiredError", + { state: Schema.String, cause: Schema.optional(Schema.Defect()) }, +) { + override get message(): string { + return `${this.state} Open Settings → SnapShots to continue setup.`; } } export const NIRI_CAPTURE_PATH = "/com/t3tools/SnapShot"; diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.ts index 3a3e84e03a9b7..7b480b36fbd12 100644 --- a/apps/desktop/src/ssh/DesktopSshEnvironment.ts +++ b/apps/desktop/src/ssh/DesktopSshEnvironment.ts @@ -23,6 +23,7 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; import * as HttpClient from "effect/http/HttpClient"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; @@ -74,11 +75,13 @@ function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) { return discoverSshHosts(input ?? {}); } +const isSshPasswordPromptError = Schema.is(SshPasswordPromptError); + export function isDesktopSshPasswordPromptCancellation( error: unknown, ): error is SshPasswordPromptError { return ( - error instanceof SshPasswordPromptError && + isSshPasswordPromptError(error) && DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause) ); } diff --git a/apps/mobile/src/components/ComposerEditor.ios.test.tsx b/apps/mobile/src/components/ComposerEditor.ios.test.tsx index d5e99928ac780..d3b7fa11a43bf 100644 --- a/apps/mobile/src/components/ComposerEditor.ios.test.tsx +++ b/apps/mobile/src/components/ComposerEditor.ios.test.tsx @@ -20,6 +20,7 @@ const native = vi.hoisted(() => ({ text: "", eventCount: 0, resetGeneration: 0, + mounts: 0, props: null as NativeProps | null, deliver: null as ((event: NativeEvent) => void) | null, })); @@ -28,6 +29,7 @@ function NativeView(props: NativeProps) { const propsRef = useRef(props); useLayoutEffect(() => { Object.assign(native, { text: "", eventCount: 0, resetGeneration: 0 }); + native.mounts += 1; }, []); useLayoutEffect(() => { propsRef.current = props; @@ -173,13 +175,16 @@ it("keeps a pending event from the previous native editor out of the selected dr ); await act(async () => renderDraft(first)); const deliverPendingEvent = native.deliver!; + const pending = { eventCount: native.eventCount + 1, resetGeneration: native.resetGeneration }; + const mounts = native.mounts; await act(async () => renderDraft(second)); + // Remounting the native view would drop the keyboard mid-edit. + expect(native.mounts).toBe(mounts); await act(async () => deliverPendingEvent({ value: "Draft A corrected", selection: { start: 17, end: 17 }, - eventCount: 1, - resetGeneration: 0, + ...pending, }), ); expect(getComposerDraftSnapshot(second).text).toBe("Draft B"); diff --git a/apps/mobile/src/components/ComposerEditor.tsx b/apps/mobile/src/components/ComposerEditor.tsx index 9a146487625be..c925113901a33 100644 --- a/apps/mobile/src/components/ComposerEditor.tsx +++ b/apps/mobile/src/components/ComposerEditor.tsx @@ -177,7 +177,7 @@ export function ComposerEditor({ <> {/* Reset revision history with the recreated iOS view without aborting context imports. */} COMPOSER_TOOLBAR_SCROLL_EPSILON, - showRightFade: metrics.offsetX < maxOffset - COMPOSER_TOOLBAR_SCROLL_EPSILON, - }; + const updateScrollEdges = useCallback(() => { + const metrics = metricsRef.current; + const maxOffset = Math.max(0, metrics.contentWidth - metrics.viewportWidth); + const showLeftFade = metrics.offsetX > COMPOSER_TOOLBAR_SCROLL_EPSILON; + const showRightFade = metrics.offsetX < maxOffset - COMPOSER_TOOLBAR_SCROLL_EPSILON; + if (metrics.showLeftFade === showLeftFade && metrics.showRightFade === showRightFade) { + return; + } + metrics.showLeftFade = showLeftFade; + metrics.showRightFade = showRightFade; + setScrollEdges({ showLeftFade, showRightFade }); + }, []); - const handleLayout = (event: LayoutChangeEvent) => { - const viewportWidth = event.nativeEvent.layout.width; - setMetrics((current) => - current.viewportWidth === viewportWidth ? current : { ...current, viewportWidth }, - ); - }; + const handleLayout = useCallback( + (event: LayoutChangeEvent) => { + const viewportWidth = event.nativeEvent.layout.width; + if (metricsRef.current.viewportWidth === viewportWidth) return; + metricsRef.current.viewportWidth = viewportWidth; + updateScrollEdges(); + }, + [updateScrollEdges], + ); - const handleContentSizeChange = (contentWidth: number) => { - setMetrics((current) => - current.contentWidth === contentWidth ? current : { ...current, contentWidth }, - ); - }; + const handleContentSizeChange = useCallback( + (contentWidth: number) => { + if (metricsRef.current.contentWidth === contentWidth) return; + metricsRef.current.contentWidth = contentWidth; + updateScrollEdges(); + }, + [updateScrollEdges], + ); - const handleScroll = (event: NativeSyntheticEvent) => { - const offsetX = event.nativeEvent.contentOffset.x; - setMetrics((current) => - Math.abs(current.offsetX - offsetX) < 1 ? current : { ...current, offsetX }, - ); - }; + const handleScroll = useCallback( + (event: NativeSyntheticEvent) => { + const offsetX = event.nativeEvent.contentOffset.x; + if (Math.abs(metricsRef.current.offsetX - offsetX) < 1) return; + metricsRef.current.offsetX = offsetX; + updateScrollEdges(); + }, + [updateScrollEdges], + ); return ( diff --git a/apps/mobile/src/components/FilePreviewModal.tsx b/apps/mobile/src/components/FilePreviewModal.tsx index 0d6ddaa2f26d3..9093507581c7a 100644 --- a/apps/mobile/src/components/FilePreviewModal.tsx +++ b/apps/mobile/src/components/FilePreviewModal.tsx @@ -1,3 +1,4 @@ +import * as Schema from "effect/Schema"; import * as Dialog from "./ui/Dialog"; import { useContext, useEffect, useEffectEvent, useState } from "react"; import { Platform } from "react-native"; @@ -21,15 +22,17 @@ export type { ResolvedFilePreviewSource, } from "./FilePreviewModal.types"; -class PreviewResolutionError extends Error { - constructor( - override readonly cause: unknown, - readonly fallbackMessage: string, - ) { - super(fallbackMessage, { cause }); +class PreviewResolutionError extends Schema.TaggedError()( + "PreviewResolutionError", + { cause: Schema.Defect(), fallbackMessage: Schema.String }, +) { + override get message(): string { + return this.fallbackMessage; } } +const isPreviewResolutionError = Schema.is(PreviewResolutionError); + interface ResolvedPreviewUri { readonly uri: string; readonly dispose?: () => void; @@ -42,7 +45,10 @@ async function resolvePreviewUri( if ("uri" in item) return { uri: item.uri }; if ("attachment" in item) { return loadLocalAttachmentPreview(item.attachment, signal).catch((error: unknown) => { - throw new PreviewResolutionError(error, "Attach the file again and retry."); + throw new PreviewResolutionError({ + cause: error, + fallbackMessage: "Attach the file again and retry.", + }); }); } // Refresh expired URLs before handing them to Quick Look or ACTION_VIEW, which retain them. @@ -52,10 +58,11 @@ async function resolvePreviewUri( return value; }) .catch((error: unknown) => { - throw new PreviewResolutionError( - error, - "Reconnect to this environment and try again. The file may have been moved or deleted.", - ); + throw new PreviewResolutionError({ + cause: error, + fallbackMessage: + "Reconnect to this environment and try again. The file may have been moved or deleted.", + }); }); return { uri: url + (item.srcFragment ?? "") }; } @@ -99,9 +106,9 @@ function ResolvedFilePreview(props: { if (progressiveGallery && index !== selectedIndex) return settle(index, null); controller.abort(); onResolutionError( - error instanceof PreviewResolutionError + isPreviewResolutionError(error) ? error - : new PreviewResolutionError(error, "Try again."), + : new PreviewResolutionError({ cause: error, fallbackMessage: "Try again." }), ); }, ); diff --git a/apps/mobile/src/features/cloud/dpop.ts b/apps/mobile/src/features/cloud/dpop.ts index b3eaf006f3d34..b427861b1e36a 100644 --- a/apps/mobile/src/features/cloud/dpop.ts +++ b/apps/mobile/src/features/cloud/dpop.ts @@ -1,6 +1,5 @@ import * as Digest from "effect/crypto/Digest"; import * as SecureRandom from "effect/crypto/SecureRandom"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; import * as Hex from "effect/encoding/Hex"; @@ -13,10 +12,10 @@ import { DpopProof } from "@t3tools/client-runtime/relay"; import { DpopPublicJwk } from "@t3tools/shared/dpopCommon"; import * as Layer from "effect/Layer"; -export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{ - readonly message: string; - readonly cause?: unknown; -}> {} +export class CloudDpopError extends Schema.TaggedError()("CloudDpopError", { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), +}) {} function cloudDpopError(message: string) { return (cause: unknown) => new CloudDpopError({ message, cause }); diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.ts index 3aef69252932f..f072f5c96d83d 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.ts @@ -1,4 +1,3 @@ -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { HttpClient } from "effect/http"; @@ -26,11 +25,14 @@ function readRelayUrl(): string | null { return resolveCloudPublicConfig().relay.url; } -export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{ - readonly message: string; - readonly cause?: unknown; - readonly traceId?: string; -}> {} +export class CloudEnvironmentLinkError extends Schema.TaggedError()( + "CloudEnvironmentLinkError", + { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + traceId: Schema.optional(Schema.String), + }, +) {} const isEnvironmentCloudApiError = Schema.is( Schema.Union([ diff --git a/apps/mobile/src/features/files/ZipArchiveView.tsx b/apps/mobile/src/features/files/ZipArchiveView.tsx index d36506a70e63f..66290e9d6c381 100644 --- a/apps/mobile/src/features/files/ZipArchiveView.tsx +++ b/apps/mobile/src/features/files/ZipArchiveView.tsx @@ -12,6 +12,7 @@ import { hostPreviewMimeTypeFromExtension, } from "@t3tools/shared/filePreview"; import { LegendList } from "@legendapp/list/react-native"; +import * as Schema from "effect/Schema"; import { fetch } from "expo/fetch"; import { File } from "expo-file-system"; import { useNavigation, usePreventRemove } from "@react-navigation/native"; @@ -68,11 +69,12 @@ interface ZipArchive { readonly fileCount: number; } -interface ZipFailure { - readonly title: string; - readonly detail: string; - readonly retry: boolean; -} +const ZipFailure = Schema.Struct({ + title: Schema.String, + detail: Schema.String, + retry: Schema.Boolean, +}); +type ZipFailure = typeof ZipFailure.Type; const SAVE_ZIP_HINT = "Save the ZIP to open it in another app."; const TOO_LARGE: ZipFailure = { @@ -91,12 +93,16 @@ const NETWORK: ZipFailure = { retry: true, }; -class ZipFailureError extends Error { - constructor(readonly failure: ZipFailure) { - super(failure.title); +class ZipFailureError extends Schema.TaggedError()("ZipFailureError", { + failure: ZipFailure, +}) { + override get message(): string { + return this.failure.title; } } +const isZipFailureError = Schema.is(ZipFailureError); + function errorMessage(cause: unknown, fallback: string) { return cause instanceof Error ? cause.message : fallback; } @@ -113,7 +119,7 @@ async function readArchiveBody( const { value, done } = await reader.read(); if (done) break; size += value.byteLength; - if (size > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE); + if (size > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE }); chunks.push(value); onProgress(size); } @@ -135,9 +141,11 @@ async function openArchive(bytes: ArrayBuffer): Promise { files = await boundedZip(bytes); } catch (cause) { throw new ZipFailureError({ - title: "Couldn't browse this ZIP", - detail: `${errorMessage(cause, "It may be incomplete or damaged.")} ${SAVE_ZIP_HINT}`, - retry: false, + failure: { + title: "Couldn't browse this ZIP", + detail: `${errorMessage(cause, "It may be incomplete or damaged.")} ${SAVE_ZIP_HINT}`, + retry: false, + }, }); } const entries = [...files].map(([path, file]): ZipEntry => { @@ -187,15 +195,15 @@ function useZipArchive(input: { // oxlint-disable-next-line react/set-state-in-effect -- A new archive load resets its progress. setState({ status: "loading", receivedBytes: 0, timeLeft: null }); void (async () => { - if (sizeBytes > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE); + if (sizeBytes > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE }); if (isLocal) { const file = new File(uri); - if ((file.size ?? 0) > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE); + if ((file.size ?? 0) > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE }); return openArchive(await file.arrayBuffer()); } const url = (await refresh()) ?? uri; const response = await fetch(url, { signal: abort.signal }); - if (!response.ok || !response.body) throw new ZipFailureError(NETWORK); + if (!response.ok || !response.body) throw new ZipFailureError({ failure: NETWORK }); const bytes = await readArchiveBody(response.body, (receivedBytes) => setState({ status: "loading", @@ -217,7 +225,7 @@ function useZipArchive(input: { if (!abort.signal.aborted) setState({ status: "failed", - failure: cause instanceof ZipFailureError ? cause.failure : NETWORK, + failure: isZipFailureError(cause) ? cause.failure : NETWORK, }); }); return () => abort.abort(); diff --git a/apps/mobile/src/features/files/sourceHighlightingState.ts b/apps/mobile/src/features/files/sourceHighlightingState.ts index 2a2db842ec4be..5dcc5eff50511 100644 --- a/apps/mobile/src/features/files/sourceHighlightingState.ts +++ b/apps/mobile/src/features/files/sourceHighlightingState.ts @@ -1,5 +1,6 @@ import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; import { Atom } from "effect/reactivity"; import { resolveHighlightLanguage } from "../../lib/highlightLanguage"; @@ -15,9 +16,10 @@ export interface SourceHighlightInput { class SourceHighlightCacheKey extends Data.Class {} -class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{ - readonly cause: unknown; -}> {} +class SourceHighlightError extends Schema.TaggedError()( + "SourceHighlightError", + { cause: Schema.Defect() }, +) {} // Highlighting is synchronous, so a cold atom resolves on its first read. The // family keeps results for files the user moves between. diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index 248c436905311..3893569c6886d 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -308,9 +308,7 @@ export function useThreadListActions(): { if (!canSnooze(thread, { now: new Date().toISOString() })) { Dialog.alert( "Could not snooze thread", - thread.hasPendingApprovals || - thread.hasPendingUserInput || - thread.pendingSubagentRequest != null + thread.hasPendingApprovals || thread.pendingSubagentRequest != null ? "This thread is waiting on you. Respond to the pending request before snoozing it." : "This thread is still starting a turn. Try again once it's running.", ); diff --git a/apps/mobile/src/features/threads/ChatGptUsageLimitNotice.tsx b/apps/mobile/src/features/threads/ChatGptUsageLimitNotice.tsx deleted file mode 100644 index faebfa5ddf927..0000000000000 --- a/apps/mobile/src/features/threads/ChatGptUsageLimitNotice.tsx +++ /dev/null @@ -1,69 +0,0 @@ -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; -import { - CHATGPT_USAGE_LIMIT_CODE, - CHATGPT_USAGE_URL, - CHATGPT_WORKSPACE_ADMIN_REQUEST, - CHATGPT_WORKSPACE_USAGE_LIMIT_CODE, -} from "@t3tools/shared/usageLimits"; -import * as Clipboard from "expo-clipboard"; -import { useState } from "react"; -import { Linking, View } from "react-native"; -import { ProviderIcon } from "../../components/ProviderIcon"; -import { AppText as Text } from "../../components/ui/AppText"; -import { Button } from "../../components/ui/Button"; - -export function ChatGptUsageLimitNotice({ thread }: { thread: EnvironmentThreadShell }) { - const [status, setStatus] = useState<"copied" | "copy-failed" | "open-failed" | null>(null); - const code = thread.runtime?.lastErrorCode; - const workspaceLimit = code === CHATGPT_WORKSPACE_USAGE_LIMIT_CODE; - if (thread.runtime?.status !== "failed" || (!workspaceLimit && code !== CHATGPT_USAGE_LIMIT_CODE)) - return null; - return ( - - - - ChatGPT usage limit reached - - - {workspaceLimit - ? status === "copied" - ? "Request copied. Send it to your workspace admin." - : "You've reached your workspace's limit for using your ChatGPT plan in other apps. Copy a request to ask your workspace admin for increased usage limits." - : "Review your usage settings in ChatGPT."} - - {workspaceLimit ? ( - + ), View: ({ children }: { children: ReactNode }) =>
{children}
, })); +vi.mock("expo-clipboard", () => ({ setStringAsync: vi.fn() })); +vi.mock("../../components/ProviderIcon", () => ({ ProviderIcon: () => null })); vi.mock("../../components/ui/AppText", () => ({ AppText: ({ children }: { children: ReactNode }) => {children}, })); @@ -27,18 +40,97 @@ import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard"; const DAY_MS = 24 * 60 * 60 * 1000; -function failedThread(resetAt: string): EnvironmentThreadShell { +function failedThread( + resetAt: string | null, + lastErrorCode?: string, + lastErrorClass = "usage_limit", +): EnvironmentThreadShell { return { id: "thread-1", updatedAt: new Date(0).toISOString(), snoozedUntil: null, latestRun: { runId: "run-1", completedAt: new Date(0).toISOString() }, limitRecovery: null, - runtime: { status: "failed", lastErrorClass: "usage_limit", usageLimitResetAt: resetAt }, + runtime: { status: "failed", lastErrorClass, lastErrorCode, usageLimitResetAt: resetAt }, } as unknown as EnvironmentThreadShell; } describe("UsageLimitRecoveryCard", () => { + // Older servers report ChatGPT sharing limits as provider errors and may store a reset. + it.each([ + [CHATGPT_USAGE_LIMIT_CODE, "usage_limit", null, ["Manage usage"]], + [CHATGPT_WORKSPACE_USAGE_LIMIT_CODE, "usage_limit", null, ["Copy request for admin"]], + [CHATGPT_USAGE_LIMIT_CODE, "provider_error", null, ["Manage usage"]], + [ + CHATGPT_USAGE_LIMIT_CODE, + "usage_limit", + new Date(DAY_MS).toISOString(), + ["Manage usage", "Resume at reset", "Snooze until reset"], + ], + ])("shows one ChatGPT notice for %s (%s, reset %s)", (code, errorClass, resetAt, actions) => { + const container = document.createElement("div"); + const root = createRoot(container); + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) }; + act(() => + root.render( + , + ), + ); + expect(container.textContent).toContain("ChatGPT usage limit reached"); + expect(container.textContent).not.toContain("did not report a reset time"); + expect([...container.querySelectorAll("button")].map((button) => button.textContent)).toEqual( + actions, + ); + }); + + it("drops a failed copy's error once a retry copies the request", async () => { + vi.mocked(Clipboard.setStringAsync) + .mockRejectedValueOnce(new Error("denied")) + .mockResolvedValueOnce(true); + const container = document.createElement("div"); + const root = createRoot(container); + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) }; + act(() => + root.render( + , + ), + ); + const copy = () => container.querySelector("button")!.click(); + await act(async () => copy()); + expect(container.textContent).toContain("Could not copy the request"); + await act(async () => copy()); + expect(container.textContent).toContain("Request copied"); + expect(container.textContent).not.toContain("Could not copy the request"); + }); + + it("ignores a second copy while the first is still in flight", async () => { + const first = Promise.withResolvers(); + vi.mocked(Clipboard.setStringAsync).mockReset().mockReturnValueOnce(first.promise); + const container = document.createElement("div"); + const root = createRoot(container); + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) }; + act(() => + root.render( + , + ), + ); + const copy = () => container.querySelector("button")!.click(); + act(() => copy()); + act(() => copy()); + expect(Clipboard.setStringAsync).toHaveBeenCalledTimes(1); + await act(async () => first.resolve(true)); + expect(container.textContent).toContain("Request copied"); + }); + it("disables Snooze once a reset more than 24.8 days away passes", () => { using _timers = { [Symbol.dispose]: () => vi.useRealTimers() }; vi.useFakeTimers({ now: 0 }); diff --git a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx index 791dc2ab5d847..27fece0272be6 100644 --- a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx +++ b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx @@ -3,9 +3,17 @@ import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime" import { AsyncResult } from "effect/reactivity"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import type { EnvironmentId } from "@t3tools/contracts"; +import { + CHATGPT_USAGE_LIMIT_CODE, + CHATGPT_USAGE_URL, + CHATGPT_WORKSPACE_ADMIN_REQUEST, + CHATGPT_WORKSPACE_USAGE_LIMIT_CODE, +} from "@t3tools/shared/usageLimits"; import * as DateTime from "effect/DateTime"; +import * as Clipboard from "expo-clipboard"; import { useState } from "react"; -import { View } from "react-native"; +import { Linking, Pressable, View } from "react-native"; +import { ProviderIcon } from "../../components/ProviderIcon"; import { AppText as Text } from "../../components/ui/AppText"; import { useDeadlinePassed } from "../../lib/clock"; import { threadEnvironment } from "../../state/threads"; @@ -30,12 +38,22 @@ export function UsageLimitRecoveryCard({ const recovery = thread.limitRecovery; const scheduled = recovery?.runId === runId && recovery?.resetAt === resetAt && recovery?.autoResume; + const [copied, setCopied] = useState(false); + const [actionPending, setActionPending] = useState(false); + const code = thread.runtime?.lastErrorCode; + // OpenAI's partner guidelines specify the ChatGPT notice and its action. + const workspaceLimit = code === CHATGPT_WORKSPACE_USAGE_LIMIT_CODE; + const chatGptLimit = workspaceLimit || code === CHATGPT_USAGE_LIMIT_CODE; if ( thread.runtime?.status !== "failed" || - thread.runtime.lastErrorClass !== "usage_limit" || + // Older servers report ChatGPT sharing limits as provider errors. + (thread.runtime.lastErrorClass !== "usage_limit" && !chatGptLimit) || !runId ) return null; + const resetText = resetAt + ? `Usage limit resets ${DateTime.toDateUtc(DateTime.makeUnsafe(resetAt)).toLocaleString()}.` + : null; const snoozed = recovery?.snooze === true && recovery.runId === runId && @@ -68,34 +86,95 @@ export function UsageLimitRecoveryCard({ setError(cause instanceof Error ? cause.message : "Could not change limit recovery."); } } + const action = workspaceLimit + ? { + label: "Copy request for admin", + role: "button" as const, + run: () => { + setError(null); + setCopied(false); + setActionPending(true); + void Clipboard.setStringAsync(CHATGPT_WORKSPACE_ADMIN_REQUEST) + .then( + () => setCopied(true), + () => setError("Could not copy the request. Try again."), + ) + .finally(() => setActionPending(false)); + }, + } + : { + label: "Manage usage", + role: "link" as const, + run: () => { + setError(null); + setActionPending(true); + void Linking.openURL(CHATGPT_USAGE_URL) + .catch(() => setError("Could not open ChatGPT. Go to chatgpt.com → Settings → Usage.")) + .finally(() => setActionPending(false)); + }, + }; return ( - - - {resetAt - ? `Usage limit resets ${DateTime.toDateUtc(DateTime.makeUnsafe(resetAt)).toLocaleString()}.` - : "The provider did not report a reset time. Retry manually when your limit is available."} - - {canSchedule ? ( - -