From 0a1bec5a980a5b2a14ebc741a85e03b72211911a Mon Sep 17 00:00:00 2001 From: Bonzi Date: Mon, 14 Sep 2026 15:04:08 +0000 Subject: [PATCH] feat: improve file downloads and APK release flow --- .env.release.example | 21 +-- apps/mobile/app.config.ts | 9 +- .../src/features/files/FileTreeBrowser.tsx | 22 ++- .../features/files/ThreadFilesRouteScreen.tsx | 29 ++- .../features/files/preload-workspace-file.ts | 2 + .../files/thread-file-navigator-pane.tsx | 3 + .../src/features/files/useFileTreeEntries.ts | 2 +- .../files/useWorkspaceFileDownload.ts | 20 +++ .../src/features/threads/fileChipMenu.test.ts | 17 +- .../src/features/threads/fileChipMenu.ts | 11 +- .../src/features/threads/useFileChipShare.ts | 22 ++- apps/server/src/assets/AssetAccess.test.ts | 39 +++++ apps/server/src/assets/AssetAccess.ts | 30 +++- apps/server/src/server.test.ts | 16 +- .../src/workspace/WorkspaceEntries.test.ts | 102 +++++++++++ apps/server/src/workspace/WorkspaceEntries.ts | 56 +++++- .../src/components/files/FileBrowserPanel.tsx | 14 +- .../src/components/files/FilePreviewPanel.tsx | 34 +++- .../files/useWorkspaceFileDownload.ts | 47 +++++ apps/web/src/state/queries.test.ts | 3 + apps/web/src/state/queries.ts | 15 +- docs/operations/fork-apk.md | 20 +++ docs/user/composer.md | 12 ++ packages/contracts/src/assets.ts | 8 +- packages/contracts/src/project.test.ts | 5 + packages/contracts/src/project.ts | 1 + packages/shared/src/filePreview.test.ts | 14 ++ packages/shared/src/filePreview.ts | 6 + scripts/build-fork-apk.sh | 0 scripts/publish-fork-apk.test.ts | 11 ++ scripts/publish-fork-apk.ts | 5 +- scripts/release-apk.sh | 165 +++++++++++++----- 32 files changed, 660 insertions(+), 101 deletions(-) create mode 100644 apps/mobile/src/features/files/useWorkspaceFileDownload.ts create mode 100644 apps/web/src/components/files/useWorkspaceFileDownload.ts mode change 100644 => 100755 scripts/build-fork-apk.sh diff --git a/.env.release.example b/.env.release.example index cf28d0f3b9..11f6e37870 100644 --- a/.env.release.example +++ b/.env.release.example @@ -1,13 +1,14 @@ -# Copy this file to .env.release. .env.release is gitignored. +# Copy this file to .env.release for local releases. Never commit .env.release. +GITEA_TOKEN= +GITEA_API_URL=https://git.molberg.cloud/api/v1/repos/alex/t3code T3CODE_APK_REPOSITORY_URL=https://git.molberg.cloud/alex/t3code -ANDROID_HOME=/path/to/Android/sdk -ANDROID_NDK_HOME=/path/to/Android/sdk/ndk/ +ANDROID_HOME=/opt/android-sdk +ANDROID_NDK_HOME=/opt/android-sdk/ndk/27.1.12297006 ANDROID_BUILD_TOOLS_VERSION=36.0.0 -APK_KEYSTORE_BASE64= -APK_KEYSTORE_PASSWORD= -APK_KEY_ALIAS= -APK_KEY_PASSWORD= -APK_RELEASE_TOKEN= +APK_KEYSTORE_BASE64= +APK_KEYSTORE_PASSWORD= +APK_KEY_ALIAS= +APK_KEY_PASSWORD= # Optional overrides: -# APK_VERSION_CODE=1001 -# APK_RELEASE_BODY=Release notes +# APK_VERSION_CODE=45 +# APK_RELEASE_BODY={"schema":1,"channel":"production"} diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 16d384219b..547b30e757 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -13,11 +13,12 @@ const repoEnv = loadRepoEnv(); Object.assign(process.env, repoEnv); const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT); +const DEFAULT_APK_REPOSITORY_URL = "https://git.molberg.cloud/alex/t3code"; const apkReleaseTag = repoEnv.T3CODE_APK_RELEASE_TAG; const apkVersionCode = apkReleaseTag ? parseAndroidApkReleaseTag(apkReleaseTag) : undefined; -const apkRepository = repoEnv.T3CODE_APK_REPOSITORY_URL - ? resolveAndroidApkRepository(repoEnv.T3CODE_APK_REPOSITORY_URL) - : undefined; +const apkRepository = resolveAndroidApkRepository( + repoEnv.T3CODE_APK_REPOSITORY_URL || DEFAULT_APK_REPOSITORY_URL, +); const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1"; const runtimeVersionPolicy = process.env.MOBILE_VERSION_POLICY ?? @@ -443,7 +444,7 @@ const config: ExpoConfig = { ...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []), ], extra: { - apkReleaseApiUrl: apkRepository?.apiUrl || null, + apkReleaseApiUrl: apkRepository.apiUrl, appVariant: APP_VARIANT, iosPersonalTeamBuild: isIosPersonalTeamBuild, relay: { diff --git a/apps/mobile/src/features/files/FileTreeBrowser.tsx b/apps/mobile/src/features/files/FileTreeBrowser.tsx index f2dfd3f15a..b62d9caa21 100644 --- a/apps/mobile/src/features/files/FileTreeBrowser.tsx +++ b/apps/mobile/src/features/files/FileTreeBrowser.tsx @@ -5,6 +5,7 @@ import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "re import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/AppText"; +import { ControlPillMenu } from "../../components/ControlPill"; import { PierreEntryIcon } from "../../components/PierreEntryIcon"; import { cn } from "../../lib/cn"; import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics"; @@ -48,10 +49,11 @@ const FileTreeRow = memo(function FileTreeRow(props: { readonly onPressDirectory: (path: string) => void; readonly onPreviewFile?: (path: string) => void; readonly onPressFile: (path: string) => void; + readonly onDownloadFile: (path: string) => void; }) { const { node, depth } = props.item; - return ( + const row = ( ); + return node.kind === "file" ? ( + { + if (nativeEvent.event === "download") props.onDownloadFile(node.path); + }} + > + {row} + + ) : ( + row + ); }); export function FileTreeBrowser(props: { @@ -118,6 +134,7 @@ export function FileTreeBrowser(props: { readonly onPreviewFile?: (path: string) => void; readonly onRefresh: () => void; readonly onSelectFile: (path: string) => void; + readonly onDownloadFile: (path: string) => void; }) { const [expandedPaths, setExpandedPaths] = useState>(() => new Set()); const [pendingSelection, setPendingSelection] = useState<{ @@ -132,6 +149,7 @@ export function FileTreeBrowser(props: { onLoadDirectory, onPreviewFile, onSelectFile, + onDownloadFile, loadedDirectories, selectedPath: controlledSelectedPath, } = props; @@ -222,12 +240,14 @@ export function FileTreeBrowser(props: { onPressDirectory={toggleDirectory} onPreviewFile={onPreviewFile} onPressFile={handleSelectFile} + onDownloadFile={onDownloadFile} /> ), [ expandedPaths, handleSelectFile, onPreviewFile, + onDownloadFile, loadedDirectories, selectedPath, toggleDirectory, diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx index 624a214e43..d32bed3b6b 100644 --- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx +++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx @@ -9,6 +9,7 @@ import { EnvironmentId, type ProjectReadFileResult, ThreadId } from "@t3tools/co import { videoMimeType } from "@t3tools/shared/video"; import { isWorkspaceBrowserPreviewPath, + isDownloadOnlyFile, isWorkspaceImagePreviewPath, mediaMimeTypeFromExtension, } from "@t3tools/shared/filePreview"; @@ -48,6 +49,7 @@ import { useAppearancePreferences } from "../settings/appearance/AppearancePrefe import { ThreadRouteScreen } from "../threads/ThreadRouteScreen"; import { FileMarkdownPreview } from "./FileMarkdownPreview"; import { FileTreeBrowser } from "./FileTreeBrowser"; +import { useWorkspaceFileDownload } from "./useWorkspaceFileDownload"; import { useFileTreeEntries } from "./useFileTreeEntries"; import { preloadWorkspaceFileContents } from "./preload-workspace-file"; import { SourceFileSurface } from "./SourceFileSurface"; @@ -114,6 +116,7 @@ function FileContent(props: { readonly resolveVideoUri: () => Promise; readonly fileContents: string | null; readonly fileError: string | null; + readonly onDownload: () => void; readonly relativePath: string; readonly threadId: ThreadId | null; readonly initialLine: number | null; @@ -183,10 +186,19 @@ function FileContent(props: { return ; } - if (props.fileError && props.fileContents === null) { + if (isDownloadOnlyFile(props.relativePath) || (props.fileError && props.fileContents === null)) { return ( - + ); } @@ -337,6 +349,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) { props.route.params, ); const revealedInspectorRef = useRef(false); + const downloadFile = useWorkspaceFileDownload(environmentId, cwd); const entriesQuery = useFileTreeEntries({ environmentId, cwd: fileInspector.supported ? null : cwd, @@ -561,6 +574,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) { onPreviewFile={handlePreviewFile} onRefresh={entriesQuery.refresh} onSelectFile={handleSelectFile} + onDownloadFile={downloadFile} /> @@ -592,6 +606,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { readonly path: string; readonly mode: FileViewMode; } | null>(null); + const downloadFile = useWorkspaceFileDownload(environmentId, cwd); const [previewRevision, setPreviewRevision] = useState(0); const previewKey = JSON.stringify([environmentId, cwd, relativePath, previewRevision]); const [fullScreenPreview, setFullScreenPreview] = useState(null); @@ -674,6 +689,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { }; const needsFileContents = relativePath !== null && + !isDownloadOnlyFile(relativePath) && !isVideoFile && !isAudioFile && (resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath)); @@ -742,6 +758,13 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { if (relativePath === null) return []; const canToggleMode = canPreview && !isImageFile && !isVideoFile && !isAudioFile; return [ + { + id: "download", + title: "Download file", + icon: "arrow.down.to.line" as const, + inline: false, + onPress: () => downloadFile(relativePath), + }, canToggleMode ? ({ id: "preview", @@ -840,6 +863,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { ].filter((action) => action !== null); }, [ appearance.codeWordBreak, + downloadFile, setCodeWordBreak, assetPreviewUri, assetPreview.refresh, @@ -1020,6 +1044,7 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { resolveVideoUri={assetPreview.refresh} fileContents={fileData?.contents ?? null} fileError={fileQuery.error} + onDownload={() => downloadFile(relativePath)} initialLine={targetLine} relativePath={relativePath} threadId={threadId} diff --git a/apps/mobile/src/features/files/preload-workspace-file.ts b/apps/mobile/src/features/files/preload-workspace-file.ts index a91e4f84b0..8db82eaa6f 100644 --- a/apps/mobile/src/features/files/preload-workspace-file.ts +++ b/apps/mobile/src/features/files/preload-workspace-file.ts @@ -1,6 +1,7 @@ import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId } from "@t3tools/contracts"; import { + isDownloadOnlyFile, isWorkspaceBrowserPreviewPath, isWorkspaceImagePreviewPath, } from "@t3tools/shared/filePreview"; @@ -30,6 +31,7 @@ export function preloadWorkspaceFileContents(input: { readonly theme: ReviewDiffTheme; }): void { if ( + isDownloadOnlyFile(input.relativePath) || isWorkspaceBrowserPreviewPath(input.relativePath) || isWorkspaceImagePreviewPath(input.relativePath) || isVideoPreviewFile(input.relativePath) diff --git a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx index 4bb847dc54..85f2519162 100644 --- a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx +++ b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx @@ -15,6 +15,7 @@ import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader"; import { useUniwindTheme } from "../../lib/useUniwindTheme"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import { FileTreeBrowser } from "./FileTreeBrowser"; +import { useWorkspaceFileDownload } from "./useWorkspaceFileDownload"; import { useFileTreeEntries } from "./useFileTreeEntries"; import { preloadWorkspaceFileContents } from "./preload-workspace-file"; import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; @@ -28,6 +29,7 @@ export function ThreadFileNavigatorPane(props: { readonly onSelectFile: (path: string) => void; }) { const [searchQuery, setSearchQuery] = useState(""); + const downloadFile = useWorkspaceFileDownload(props.environmentId, props.cwd); const { toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout(); const { themeAppearance: highlightTheme } = useAppearancePreferences(); const theme = useUniwindTheme(); @@ -91,6 +93,7 @@ export function ThreadFileNavigatorPane(props: { onPreviewFile={handlePreviewFile} onRefresh={entriesQuery.refresh} onSelectFile={props.onSelectFile} + onDownloadFile={downloadFile} /> ); diff --git a/apps/mobile/src/features/files/useFileTreeEntries.ts b/apps/mobile/src/features/files/useFileTreeEntries.ts index 604fb3bd52..dc66e5dfbc 100644 --- a/apps/mobile/src/features/files/useFileTreeEntries.ts +++ b/apps/mobile/src/features/files/useFileTreeEntries.ts @@ -26,7 +26,7 @@ export function useFileTreeEntries(input: { searching && debouncedQuery.length > 0 && cwd !== null && environmentId !== null ? projectEnvironment.searchEntries({ environmentId, - input: { cwd, query: debouncedQuery, limit: 200 }, + input: { cwd, query: debouncedQuery, limit: 200, includeIgnored: true }, }) : null, ); diff --git a/apps/mobile/src/features/files/useWorkspaceFileDownload.ts b/apps/mobile/src/features/files/useWorkspaceFileDownload.ts new file mode 100644 index 0000000000..92cdd69d81 --- /dev/null +++ b/apps/mobile/src/features/files/useWorkspaceFileDownload.ts @@ -0,0 +1,20 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import { useCallback } from "react"; + +import { useFileDownload } from "../threads/useFileChipShare"; +import { basename } from "./filePath"; + +export function useWorkspaceFileDownload(environmentId: EnvironmentId | null, cwd: string | null) { + const download = useFileDownload(environmentId, "workspace-file-download"); + return useCallback( + (path: string) => { + if (cwd === null) return; + download({ + name: basename(path), + mimeType: "application/octet-stream", + resource: { _tag: "draft-workspace-file", cwd, path, download: true }, + }); + }, + [cwd, download], + ); +} diff --git a/apps/mobile/src/features/threads/fileChipMenu.test.ts b/apps/mobile/src/features/threads/fileChipMenu.test.ts index 1627a72da5..1f1a2e13d0 100644 --- a/apps/mobile/src/features/threads/fileChipMenu.test.ts +++ b/apps/mobile/src/features/threads/fileChipMenu.test.ts @@ -35,11 +35,13 @@ describe("fileChipMenu", () => { actions: [ { id: "copy-full-path", title: "Copy full path" }, { id: "open-file", title: "Open in file viewer" }, + { id: "save", title: "Download file" }, ], }); expect(fileChipMenu({ relativePath: "src/app.ts" }).actions.map(({ id }) => id)).toEqual([ "copy-relative-path", "open-file", + "save", ]); }); }); @@ -60,12 +62,12 @@ describe("file chip downloads", () => { const target = resolveFileChipTarget(href, "/repo")!; expect(fileChipMenu(target).actions).toContainEqual({ id: "save", - title: "Save or share", + title: "Download file", }); expect(fileChipShareSource(target, threadId)).toEqual({ name: path.split("/").at(-1), mimeType, - resource: { _tag: "media-file", threadId, path }, + resource: { _tag: "media-file", threadId, path, download: true }, }); }); @@ -77,11 +79,14 @@ describe("file chip downloads", () => { }); }); - it("does not offer downloads the host asset endpoint cannot serve", () => { - for (const href of ["src/app.ts", "/tmp/archive.zip", "/tmp/clip.mp4.txt"]) { + it("offers explicit downloads for source files and unsupported binary formats", () => { + for (const href of ["src/app.ts", "/tmp/archive.zip", "/tmp/clip.mp4.txt", "/tmp/app.apk"]) { const target = resolveFileChipTarget(href, "/repo")!; - expect(fileChipShareSource(target, threadId)).toBeNull(); - expect(fileChipMenu(target).actions.some(({ id }) => id === "save")).toBe(false); + expect(fileChipShareSource(target, threadId)).toMatchObject({ + mimeType: "application/octet-stream", + resource: { download: true, threadId }, + }); + expect(fileChipMenu(target).actions.some(({ id }) => id === "save")).toBe(true); } }); }); diff --git a/apps/mobile/src/features/threads/fileChipMenu.ts b/apps/mobile/src/features/threads/fileChipMenu.ts index 9f82e08944..b5c3e79def 100644 --- a/apps/mobile/src/features/threads/fileChipMenu.ts +++ b/apps/mobile/src/features/threads/fileChipMenu.ts @@ -44,8 +44,10 @@ function fileChipMetadata(target: FileChipTarget) { if (!path) return null; const name = fileBasename(path); const dot = name.lastIndexOf("."); - const mimeType = dot < 0 ? null : hostPreviewMimeTypeFromExtension(name.slice(dot)); - return mimeType ? { path, name, mimeType } : null; + const mimeType = + (dot < 0 ? null : hostPreviewMimeTypeFromExtension(name.slice(dot))) ?? + "application/octet-stream"; + return { path, name, mimeType }; } /** Use literal resolved paths so encoded filename characters are not decoded twice. */ @@ -55,12 +57,11 @@ export function fileChipShareSource(target: FileChipTarget, threadId: ThreadId) ? { name: metadata.name, mimeType: metadata.mimeType, - resource: { _tag: "media-file" as const, threadId, path: metadata.path }, + resource: { _tag: "media-file" as const, threadId, path: metadata.path, download: true }, } : null; } -/** Saving is available for the media and documents the host asset endpoint can serve. */ export function fileChipMenu(target: FileChipTarget): MarkdownFileContextMenu { return { title: target.fullPath ?? target.relativePath ?? "", @@ -72,7 +73,7 @@ export function fileChipMenu(target: FileChipTarget): MarkdownFileContextMenu { ? [ { id: "save", - title: "Save or share", + title: "Download file", }, ] : []), diff --git a/apps/mobile/src/features/threads/useFileChipShare.ts b/apps/mobile/src/features/threads/useFileChipShare.ts index 587aa8ad95..3c12ac40be 100644 --- a/apps/mobile/src/features/threads/useFileChipShare.ts +++ b/apps/mobile/src/features/threads/useFileChipShare.ts @@ -1,5 +1,5 @@ import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets"; -import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import type { AssetResource, EnvironmentId, ThreadId } from "@t3tools/contracts"; import * as Option from "effect/Option"; import { useCallback, useEffect, useLayoutEffect, useRef } from "react"; import { Alert } from "react-native"; @@ -16,6 +16,17 @@ export function useFileChipShare( threadId: ThreadId, sourceIdentifier: string, ) { + const download = useFileDownload(environmentId, sourceIdentifier); + return useCallback( + (target: FileChipTarget) => { + const source = fileChipShareSource(target, threadId); + if (source) download(source); + }, + [download, threadId], + ); +} + +export function useFileDownload(environmentId: EnvironmentId | null, sourceIdentifier: string) { const connection = usePreparedConnection(environmentId); const httpBaseUrl = Option.isSome(connection) ? connection.value.httpBaseUrl : null; const createUrl = useAtomQueryRunner(assetEnvironment.createUrl, { @@ -30,9 +41,8 @@ export function useFileChipShare( useEffect(() => () => requestRef.current?.abort(), []); const share = useCallback( - (target: FileChipTarget) => { - const source = fileChipShareSource(target, threadId); - if (!source || requestRef.current) return; + (source: { name: string; mimeType: string; resource: AssetResource }) => { + if (environmentId === null || requestRef.current) return; const request = new AbortController(); requestRef.current = request; const httpBaseUrl = connectionRef.current; @@ -53,7 +63,7 @@ export function useFileChipShare( .catch((error: unknown) => { if (!request.signal.aborted) { Alert.alert( - "Could not share file", + "Could not download file", error instanceof Error ? error.message : "Try again.", ); } @@ -64,7 +74,7 @@ export function useFileChipShare( } }); }, - [createUrl, environmentId, sourceIdentifier, threadId], + [createUrl, environmentId, sourceIdentifier], ); return share; } diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 225910e384..2e1576147a 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -47,6 +47,45 @@ const testLayer = Layer.mergeAll( ).pipe(Layer.provideMerge(NodeServices.layer)); describe("AssetAccess", () => { + it.effect("downloads arbitrary files with exact signed access and original bytes", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-download-" }); + const threadId = ThreadId.make("thread-1"); + for (const name of ["app.apk", "source.ts", "archive.zip", "page.html", "résumé.txt"]) { + const filePath = path.join(root, name); + const bytes = new Uint8Array([0, 255, 80, 75, 13, 10]); + yield* fs.writeFile(filePath, bytes); + for (const resource of [ + { _tag: "media-file" as const, threadId, path: filePath, download: true }, + { _tag: "workspace-file" as const, threadId, path: name, download: true }, + { _tag: "draft-workspace-file" as const, cwd: root, path: name, download: true }, + ]) { + const result = yield* issueAssetUrl({ resource, workspaceRoot: root }); + const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const separator = suffix.indexOf("/"); + const token = suffix.slice(0, separator); + const asset = yield* resolveAsset(token, suffix.slice(separator + 1)); + expect(asset).toMatchObject({ + kind: "file", + download: true, + fileName: name, + mimeType: "application/octet-stream", + }); + if (asset?.kind !== "file") throw new Error("Expected a downloadable file"); + const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset)); + expect(response.headers.get("content-disposition")).toContain("attachment;"); + expect(new Uint8Array(yield* Effect.promise(() => response.arrayBuffer()))).toEqual( + bytes, + ); + expect(yield* resolveAsset(token, "sibling.txt")).toBeNull(); + expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull(); + } + } + }).pipe(Effect.provide(testLayer)), + ); + it.effect("issues exact URLs for media and browser documents outside the workspace", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index 700aeacb19..8b667a628a 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -98,6 +98,7 @@ const AssetClaimsSchema = Schema.Union([ Schema.Struct({ version: Schema.Literal(1), kind: Schema.Literal("media-file-exact"), + download: Schema.optionalKey(Schema.Boolean), filePath: Schema.String, device: Schema.String, inode: Schema.String, @@ -274,10 +275,12 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe if (!canonicalFile) { return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource }); } - if (hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) { + const download = "download" in input.resource && input.resource.download === true; + if (!download && hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) { return yield* new AssetPreviewTypeValidationError({ resource: input.resource }); } - const wantsDimensions = HEADER_IMAGE_EXTENSIONS.has(path.extname(canonicalFile).toLowerCase()); + const wantsDimensions = + !download && HEADER_IMAGE_EXTENSIONS.has(path.extname(canonicalFile).toLowerCase()); const opened = yield* openMediaFile(canonicalFile).pipe( Effect.flatMap((file) => file === null @@ -304,6 +307,7 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe claims: { version: 1 as const, kind: "media-file-exact" as const, + ...(download ? { download: true } : {}), filePath: canonicalFile, ...opened.identity, expiresAt: input.expiresAt, @@ -338,7 +342,8 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA }), ), ); - if (!isWorkspacePreviewEntryPath(resolved.relativePath)) { + const download = "download" in input.resource && input.resource.download === true; + if (!download && !isWorkspacePreviewEntryPath(resolved.relativePath)) { return yield* new AssetPreviewTypeValidationError({ resource: input.resource, }); @@ -360,6 +365,13 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA resource: input.resource, }); } + if (download) { + return yield* finalizeAbsoluteMediaFileAsset({ + requestedPath: canonicalFile, + resource: input.resource, + expiresAt: input.expiresAt, + }); + } const canonicalWorkspaceRoot = yield* fileSystem.realPath(input.workspaceRoot).pipe( Effect.mapError( (cause) => @@ -778,7 +790,9 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* ( Effect.orElseSucceed(() => null), ); if (canonicalFile !== claims.filePath) return null; - const mimeType = hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)); + const mimeType = claims.download + ? "application/octet-stream" + : hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)); if (!mimeType) return null; const file = yield* openMediaFile(canonicalFile, claims).pipe( Effect.tapError((cause) => @@ -787,7 +801,13 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* ( Effect.orElseSucceed(() => null), ); return file - ? ({ kind: "file", path: canonicalFile, mimeType, file } satisfies ResolvedAsset) + ? ({ + kind: "file", + path: canonicalFile, + mimeType, + file, + ...(claims.download ? { download: true, fileName: path.basename(canonicalFile) } : {}), + } satisfies ResolvedAsset) : null; } if (claims.kind === "workspace-file-exact") { diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index af934c59d4..e5bf7ee86d 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -6866,7 +6866,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive), ); - it.effect("routes websocket rpc projects.searchEntries excludes gitignored files", () => + it.effect("routes projects.searchEntries with optional ignored files", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -6920,6 +6920,20 @@ it.layer(NodeServices.layer)("server router seam", (it) => { assert.equal(response.entries.length, 0); assert.equal(response.truncated, false); + const allFiles = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.projectsSearchEntries]({ + cwd: workspaceDir, + query: "ignored-search-target", + limit: 10, + includeIgnored: true, + }), + ), + ); + assert.deepEqual(allFiles.entries, [ + { path: ".venv/lib/ignored-search-target.ts", kind: "file" }, + ]); + assert.equal(allFiles.truncated, false); }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive), ); diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index 6013f978ed..8e496f16ba 100644 --- a/apps/server/src/workspace/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/WorkspaceEntries.test.ts @@ -12,6 +12,7 @@ import { vi } from "vite-plus/test"; import * as ServerConfig from "../config.ts"; import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; +import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import * as VcsProcess from "../vcs/VcsProcess.ts"; import * as WorkspaceEntries from "./WorkspaceEntries.ts"; import * as WorkspacePaths from "./WorkspacePaths.ts"; @@ -77,6 +78,8 @@ const searchWorkspaceEntries = (input: { query: string; limit: number; kind?: "file" | "directory"; + includeIgnored?: boolean; + imageOnly?: boolean; }) => Effect.gen(function* () { const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; @@ -95,6 +98,105 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceEntries", (it) => { vi.restoreAllMocks(); }); + describe("current filesystem search", () => { + it.effect( + "finds ignored APKs, hidden files, and nested build outputs without exposing git internals", + () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ git: true }); + yield* writeTextFile(cwd, ".gitignore", "build/\n*.apk\n.cache/\n"); + yield* writeTextFile(cwd, "build/outputs/app-release.apk", "binary artifact"); + yield* writeTextFile(cwd, ".cache/APP.APK"); + yield* writeTextFile(cwd, "download.apk"); + yield* writeTextFile(cwd, "mapKeys.ts"); + yield* writeTextFile(cwd, ".git/private.apk"); + yield* writeTextFile(cwd, "nested/.git/private.apk"); + const indexed = yield* searchWorkspaceEntries({ cwd, query: ".apk", limit: 200 }); + expect(indexed.entries.some((entry) => entry.path.toLowerCase().endsWith(".apk"))).toBe( + false, + ); + const result = yield* searchWorkspaceEntries({ + cwd, + query: ".ApK", + limit: 200, + includeIgnored: true, + }); + expect(result.entries.map((entry) => entry.path).sort()).toEqual([ + ".cache/APP.APK", + "build/outputs/app-release.apk", + "download.apk", + ]); + expect(result.truncated).toBe(false); + }), + ); + + it.effect("reflects created and deleted files without refreshing an index", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir(); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const input = { cwd, query: "apk", limit: 200, includeIgnored: true }; + expect((yield* searchWorkspaceEntries(input)).entries).toEqual([]); + yield* writeTextFile(cwd, "build/new.apk"); + expect((yield* searchWorkspaceEntries(input)).entries).toEqual([ + { path: "build/new.apk", kind: "file" }, + ]); + yield* fs.remove(path.join(cwd, "build/new.apk")); + expect((yield* searchWorkspaceEntries(input)).entries).toEqual([]); + }), + ); + + it.effect("bounds results and preserves kind, image, and multi-part query filters", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir(); + yield* writeTextFile(cwd, "build/one.apk"); + yield* writeTextFile(cwd, "build/two.apk"); + yield* writeTextFile(cwd, "build/icon.png"); + const input = { cwd, query: "build", limit: 200, includeIgnored: true }; + expect( + yield* searchWorkspaceEntries({ ...input, query: "build apk", limit: 1 }), + ).toMatchObject({ + entries: [expect.objectContaining({ kind: "file" })], + truncated: true, + }); + expect( + yield* searchWorkspaceEntries({ ...input, query: "build/apk", limit: 2 }), + ).toMatchObject({ + entries: expect.arrayContaining([ + { path: "build/one.apk", kind: "file" }, + { path: "build/two.apk", kind: "file" }, + ]), + truncated: false, + }); + expect((yield* searchWorkspaceEntries({ ...input, kind: "directory" })).entries).toEqual([ + { path: "build", kind: "directory" }, + ]); + expect( + (yield* searchWorkspaceEntries({ ...input, kind: "directory", imageOnly: true })).entries, + ).toEqual([{ path: "build/icon.png", kind: "file" }]); + }), + ); + + it.effect.skipIf(!symlinksSupported)( + "does not follow symlinks outside the workspace or into cycles", + () => + Effect.gen(function* () { + const cwd = yield* makeTempDir(); + const outside = yield* makeTempDir(); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* writeTextFile(cwd, "inside.apk"); + yield* writeTextFile(outside, "outside.apk"); + yield* fs.symlink(outside, path.join(cwd, "outside")); + yield* fs.symlink(cwd, path.join(cwd, "loop")); + expect( + (yield* searchWorkspaceEntries({ cwd, query: "apk", limit: 200, includeIgnored: true })) + .entries, + ).toEqual([{ path: "inside.apk", kind: "file" }]); + }), + ); + }); + describe("list", () => { it.effect("lists immediate children including ignored and empty directories", () => Effect.gen(function* () { diff --git a/apps/server/src/workspace/WorkspaceEntries.ts b/apps/server/src/workspace/WorkspaceEntries.ts index d575f944d8..97d84c9971 100644 --- a/apps/server/src/workspace/WorkspaceEntries.ts +++ b/apps/server/src/workspace/WorkspaceEntries.ts @@ -22,6 +22,7 @@ import type { import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path"; import { normalizeSearchQuery } from "@t3tools/shared/searchRanking"; +import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview"; import { expandHomePathWith } from "../pathExpansion.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; @@ -236,8 +237,61 @@ export const make = Effect.gen(function* () { function* (input) { const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd); const normalizedQuery = normalizeSearchQuery(input.query, { - trimLeadingPattern: /^[@./]+/, + trimLeadingPattern: input.includeIgnored ? /^(?:@|\.[/\\])+/ : /^[@./]+/, }); + if (input.includeIgnored) { + return yield* Effect.tryPromise({ + try: async (signal) => { + const entries: ProjectEntry[] = []; + const directories = [""]; + const tokens = normalizedQuery.split(/[\s/\\]+/).filter(Boolean); + let truncated = false; + while (directories.length > 0) { + signal.throwIfAborted(); + const relativeDirectory = directories.pop()!; + let directory; + try { + directory = await NodeFSP.opendir(path.join(normalizedCwd, relativeDirectory)); + } catch (cause) { + const code = (cause as NodeJS.ErrnoException).code; + if (code === "ENOENT" || code === "ENOTDIR") continue; + if (code === "EACCES" || code === "EPERM") { + truncated = true; + continue; + } + throw cause; + } + for await (const child of directory) { + signal.throwIfAborted(); + if (child.name === ".git" || (!child.isDirectory() && !child.isFile())) continue; + const relativePath = relativeDirectory + ? `${relativeDirectory}/${child.name}` + : child.name; + const kind = child.isDirectory() ? "directory" : "file"; + if (kind === "directory") directories.push(relativePath); + if ( + input.imageOnly + ? kind !== "file" || !isWorkspaceImagePreviewPath(relativePath) + : input.kind && input.kind !== kind + ) + continue; + if (!tokens.every((token) => relativePath.toLowerCase().includes(token))) continue; + if (entries.length === input.limit) return { entries, truncated: true }; + entries.push({ path: relativePath, kind }); + } + } + return { entries, truncated }; + }, + catch: (cause) => + new WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed({ + cwd: normalizedCwd, + queryLength: normalizedQuery.length, + pageSize: input.limit, + reason: "Failed to search current workspace files.", + cause, + }), + }); + } return yield* Effect.gen(function* () { const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex; return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly); diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 750fa3c7d1..a4b0603c8f 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -25,6 +25,7 @@ import { createFileTreeDragMentionController } from "./fileTreeDragMention"; import { areAllDirectoriesExpanded, setAllDirectoriesExpanded } from "./fileTreeExpansion"; import { buildFileTreePathUpdates } from "./fileTreePathReconciliation"; import { useDirectoryEntries } from "./useDirectoryEntries"; +import { useWorkspaceFileDownload } from "./useWorkspaceFileDownload"; import { useProjectPathSearch } from "~/state/queries"; interface FileBrowserPanelProps { @@ -104,6 +105,7 @@ export default function FileBrowserPanel({ workspaceMutationId, }: FileBrowserPanelProps) { const { resolvedTheme } = useTheme(); + const downloadFile = useWorkspaceFileDownload(environmentId, cwd); const composerRef = useComposerHandleContext(); const { entries: directoryEntries, @@ -115,7 +117,10 @@ export default function FileBrowserPanel({ } = useDirectoryEntries(environmentId, cwd); const [query, setQuery] = useState(""); const [expandAll, setExpandAll] = useState(false); - const pathSearch = useProjectPathSearch({ environmentId, cwd, query: query.slice(0, 256) }, 200); + const pathSearch = useProjectPathSearch( + { environmentId, cwd, query: query.slice(0, 256), includeIgnored: true }, + 200, + ); const entries = useMemo(() => { const result = new Map(directoryEntries.map((entry) => [entry.path, entry])); if (query.trim() && !pathSearch.isPending) { @@ -179,9 +184,16 @@ export default function FileBrowserPanel({ [ { id: "copy-mention", label: "Copy mention" }, { id: "add-to-chat", label: "Add to chat" }, + ...(entryKindsRef.current.get(relativePath) === "file" + ? [{ id: "download", label: "Download file" }] + : []), ], position, ); + if (clicked === "download") { + void downloadFile(relativePath); + return; + } if (clicked === "copy-mention") { try { await writeTextToClipboard(mention); diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 37228d69ce..209539fa0e 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -9,6 +9,7 @@ import type { import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview"; import { isWorkspaceAudioPreviewPath, + isDownloadOnlyFile, isWorkspaceImagePreviewPath, isWorkspaceVideoPreviewPath, } from "@t3tools/shared/filePreview"; @@ -21,13 +22,14 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { mediaFileReference } from "@t3tools/client-runtime/media-reference"; -import { Code2, Eye, FolderTree, Globe2, Table2, WrapTextIcon } from "lucide-react"; +import { Code2, Download, Eye, FolderTree, Globe2, Table2, WrapTextIcon } from "lucide-react"; import * as Schema from "effect/Schema"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview"; import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls"; import { OpenInPicker } from "~/components/chat/OpenInPicker"; +import { Button } from "~/components/ui/button"; import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer"; import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions"; import { useRemoteOpenState } from "~/remoteOpen"; @@ -55,6 +57,7 @@ import { AudioPreview } from "./AudioPreview"; import { BrowserDocumentFrame, isPdfPreviewFile } from "./BrowserDocumentFrame"; import { DelimitedTablePreview } from "./DelimitedTablePreview"; import FileBrowserPanel from "./FileBrowserPanel"; +import { useWorkspaceFileDownload } from "./useWorkspaceFileDownload"; import { FileBreadcrumbs } from "./FileBreadcrumbs"; import { FileMarkdownPreview } from "./FileMarkdownPreview"; import { @@ -921,6 +924,8 @@ export default function FilePreviewPanel({ workspaceMutationId, }: FilePreviewPanelProps) { const { resolvedTheme } = useTheme(); + const downloadFile = useWorkspaceFileDownload(environmentId, cwd); + const downloadOnly = relativePath !== null && isDownloadOnlyFile(relativePath); const wordWrap = useClientSettings((settings) => settings.wordWrap); const primaryEnvironmentId = usePrimaryEnvironmentId(); const remoteOpenState = useRemoteOpenState(environmentId); @@ -945,7 +950,7 @@ export default function FilePreviewPanel({ environmentId, cwd, relativePath, - attachment === undefined && !isMedia && !isPdf, + attachment === undefined && !isMedia && !isPdf && !downloadOnly, ); const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen); const showExplorer = shouldShowFileExplorer({ @@ -1108,6 +1113,14 @@ export default function FilePreviewPanel({ enableShortcut={false} /> ) : null} + {relativePath && attachment === undefined ? ( + void downloadFile(relativePath)} + > + + + ) : null} {canToggleRendered && renderedMode ? ( - ) : relativePath && file.error && file.data === null ? ( -
- {file.error} + ) : relativePath && (downloadOnly || (file.error && file.data === null)) ? ( +
+

+ {downloadOnly + ? "This file cannot be previewed. Would you like to download it?" + : file.error} +

+
) : relativePath && file.data === null ? (
diff --git a/apps/web/src/components/files/useWorkspaceFileDownload.ts b/apps/web/src/components/files/useWorkspaceFileDownload.ts new file mode 100644 index 0000000000..d5c831a884 --- /dev/null +++ b/apps/web/src/components/files/useWorkspaceFileDownload.ts @@ -0,0 +1,47 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import { useCallback } from "react"; + +import { resolveAssetUrl } from "~/assets/assetUrls"; +import { toastManager } from "~/components/ui/toast"; +import { assetEnvironment } from "~/state/assets"; +import { usePreparedConnection } from "~/state/session"; +import { useAtomQueryRunner } from "~/state/use-atom-query-runner"; + +export function useWorkspaceFileDownload(environmentId: EnvironmentId, cwd: string) { + const connection = usePreparedConnection(environmentId); + const httpBaseUrl = connection._tag === "Some" ? connection.value.httpBaseUrl : null; + const createUrl = useAtomQueryRunner(assetEnvironment.createUrl, { + refresh: true, + reportFailure: false, + }); + return useCallback( + async (path: string) => { + try { + if (httpBaseUrl === null) throw new Error("Reconnect to the environment and try again."); + const result = await createUrl({ + environmentId, + input: { + resource: { _tag: "draft-workspace-file", cwd, path, download: true }, + }, + }); + const url = + result._tag === "Success" ? resolveAssetUrl(httpBaseUrl, result.value.relativeUrl) : null; + if (url === null) + throw new Error("The file could not be downloaded. Reconnect and try again."); + const anchor = document.createElement("a"); + anchor.href = url; + anchor.download = path.split(/[\\/]/).at(-1) ?? "download"; + document.body.append(anchor); + anchor.click(); + anchor.remove(); + } catch (error) { + toastManager.add({ + type: "error", + title: "Could not download file", + description: error instanceof Error ? error.message : "Try again.", + }); + } + }, + [createUrl, cwd, environmentId, httpBaseUrl], + ); +} diff --git a/apps/web/src/state/queries.test.ts b/apps/web/src/state/queries.test.ts index 811f4211ee..ec67cfc75f 100644 --- a/apps/web/src/state/queries.test.ts +++ b/apps/web/src/state/queries.test.ts @@ -22,5 +22,8 @@ describe("areProjectPathSearchTargetsEqual", () => { expect(areProjectPathSearchTargetsEqual(target, { ...target, query: "readme" })).toBe(false); expect(areProjectPathSearchTargetsEqual(target, { ...target, kind: "file" })).toBe(false); expect(areProjectPathSearchTargetsEqual(target, { ...target, imageOnly: true })).toBe(false); + expect(areProjectPathSearchTargetsEqual(target, { ...target, includeIgnored: true })).toBe( + false, + ); }); }); diff --git a/apps/web/src/state/queries.ts b/apps/web/src/state/queries.ts index a16c0921a7..aab76fd32f 100644 --- a/apps/web/src/state/queries.ts +++ b/apps/web/src/state/queries.ts @@ -205,6 +205,7 @@ export function usePaginatedBranches(target: VcsRefTarget) { } type ProjectPathSearchTarget = ComposerPathSearchTarget & { + readonly includeIgnored?: boolean | undefined; readonly kind?: ProjectEntryKind | undefined; readonly imageOnly?: boolean | undefined; }; @@ -218,7 +219,8 @@ export function areProjectPathSearchTargetsEqual( left.cwd === right.cwd && left.query === right.query && left.kind === right.kind && - left.imageOnly === right.imageOnly + left.imageOnly === right.imageOnly && + left.includeIgnored === right.includeIgnored ); } @@ -235,8 +237,16 @@ export function useProjectPathSearch( query: target.query == null ? null : target.query.trim(), kind: target.kind, imageOnly: target.imageOnly, + includeIgnored: target.includeIgnored, }), - [target.cwd, target.environmentId, target.imageOnly, target.kind, target.query], + [ + target.cwd, + target.environmentId, + target.imageOnly, + target.includeIgnored, + target.kind, + target.query, + ], ); const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS); const result = useEnvironmentQuery( @@ -252,6 +262,7 @@ export function useProjectPathSearch( limit, ...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}), ...(debouncedTarget.imageOnly ? { imageOnly: true } : {}), + ...(debouncedTarget.includeIgnored ? { includeIgnored: true } : {}), }, }) : null, diff --git a/docs/operations/fork-apk.md b/docs/operations/fork-apk.md index 56613b6514..697a76cf89 100644 --- a/docs/operations/fork-apk.md +++ b/docs/operations/fork-apk.md @@ -50,6 +50,26 @@ and distribute an APK built for the new repository URL. Keep the same signing ke across the move and ensure the release token has write access to the new owner’s repository. +## Local release + +For a local build from a checkout, copy the example configuration and run the +release script exactly like the MG Utility release flow: + +```sh +cp .env.release.example .env.release +$EDITOR .env.release +./scripts/release-apk.sh --dry-run # prints the next apk- +./scripts/release-apk.sh # builds, signs, uploads, publishes +``` + +`GITEA_TOKEN` (or `APK_RELEASE_TOKEN`) must be present in `.env.release`. The +keystore, Android SDK, NDK, and Expo toolchain still need to match the build +script. The release body defaults to a `production` JSON envelope +(`schema: 1, channel, versionCode, versionName, branch, commit, sha256`); +`APK_RELEASE_BODY` overrides the entire body when set. `APK_VERSION_CODE` pins +the next release only when it exceeds the highest existing `apk-*` tag on the +target Gitea repository. + ## Publish an update Push a tag of the form `apk-` on the commit to release. For example, diff --git a/docs/user/composer.md b/docs/user/composer.md index 4da4522158..b39ed4f2df 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -196,6 +196,18 @@ File links refer to the environment's machine, including when you connect remote Previews use the original file, even outside the workspace. Moving or deleting it can break the preview, so save a copy if you need to keep it. +## Downloading files + +To download a workspace file, right-click it in the file explorer on web or desktop, +or touch and hold it in Files on mobile, then choose **Download file**. Files such +as APKs and archives offer a download instead of a preview when you follow an +agent's file link. Nothing downloads until you choose to proceed. Mobile uses the +device's save/share sheet so you can choose where to keep or send the file. + +File explorer search includes hidden and Git-ignored files, including generated +build outputs. Refresh the file explorer to pick up newly created or deleted files. +Broad searches show up to 200 matches; narrow the query if results are truncated. + ## Files outside the workspace Follow an agent's file link to read a report or other file outside the workspace. diff --git a/packages/contracts/src/assets.ts b/packages/contracts/src/assets.ts index 6447aab225..fcece01b85 100644 --- a/packages/contracts/src/assets.ts +++ b/packages/contracts/src/assets.ts @@ -14,19 +14,23 @@ const ASSET_PATH_MAX_LENGTH = 1024; export const AssetResource = Schema.Union([ Schema.TaggedStruct("workspace-file", { threadId: ThreadId, + download: Schema.optionalKey(Schema.Boolean), path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)), }), // One file served in place from anywhere the environment host can read: - // images, videos, HTML, and PDF. An absolute path may lie outside the - // workspace; a relative one resolves against the thread's workspace. + // previews of images, videos, HTML, and PDF, or explicit downloads of any type. + // An absolute path may lie outside the workspace; a relative one resolves + // against the thread's workspace. Schema.TaggedStruct("media-file", { threadId: ThreadId, + download: Schema.optionalKey(Schema.Boolean), path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)), }), // A workspace file named by a draft that has no thread yet. The draft names // its workspace root explicitly instead of resolving one from a thread. Schema.TaggedStruct("draft-workspace-file", { cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)), + download: Schema.optionalKey(Schema.Boolean), path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)), }), Schema.TaggedStruct("attachment", { diff --git a/packages/contracts/src/project.test.ts b/packages/contracts/src/project.test.ts index 8e6771cba8..06832e44bc 100644 --- a/packages/contracts/src/project.test.ts +++ b/packages/contracts/src/project.test.ts @@ -14,6 +14,11 @@ const decodeSearchEntriesInput = Schema.decodeUnknownSync(ProjectSearchEntriesIn const decodeSearchContentsInput = Schema.decodeUnknownSync(ProjectSearchContentsInput); describe("project search inputs", () => { + it("allows file browsers to include ignored files without changing legacy requests", () => { + const input = { cwd: "/workspace", query: ".apk", limit: 200 }; + expect(decodeSearchEntriesInput(input).includeIgnored).toBeUndefined(); + expect(decodeSearchEntriesInput({ ...input, includeIgnored: true }).includeIgnored).toBe(true); + }); it("allows an empty entries query for bounded frecency browsing", () => { const decoded = decodeSearchEntriesInput({ cwd: "/workspace", diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts index 3858c241c2..aebde35b52 100644 --- a/packages/contracts/src/project.ts +++ b/packages/contracts/src/project.ts @@ -22,6 +22,7 @@ export const ProjectSearchEntriesInput = Schema.Struct({ limit: PositiveInt.check(Schema.isLessThanOrEqualTo(PROJECT_SEARCH_ENTRIES_MAX_LIMIT)), kind: Schema.optional(ProjectEntryKind), imageOnly: Schema.optional(Schema.Boolean), + includeIgnored: Schema.optional(Schema.Boolean), }); export type ProjectSearchEntriesInput = typeof ProjectSearchEntriesInput.Type; diff --git a/packages/shared/src/filePreview.test.ts b/packages/shared/src/filePreview.test.ts index 34d619e7a7..8ffb716040 100644 --- a/packages/shared/src/filePreview.test.ts +++ b/packages/shared/src/filePreview.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vite-plus/test"; import { filePreviewKind, + isDownloadOnlyFile, decodeFilePreviewText, FILE_TEXT_PREVIEW_MAX_BYTES, hostPreviewMimeTypeFromExtension, @@ -14,6 +15,19 @@ import { } from "./filePreview.ts"; describe("workspace file previews", () => { + it.each(["app.apk", "APP.APK", "build/app.aab", "archive.tar.gz", "installer.exe"])( + "offers a download instead of previewing %s", + (path) => { + expect(isDownloadOnlyFile(path)).toBe(true); + }, + ); + + it.each(["app.apk.ts", "README", "source.custom", "image.png", "report.pdf"])( + "retains preview behavior for %s", + (path) => { + expect(isDownloadOnlyFile(path)).toBe(false); + }, + ); it.each(["report.html", "report.HTM", "document.pdf?download=1"])( "recognizes browser preview path %s", (path) => { diff --git a/packages/shared/src/filePreview.ts b/packages/shared/src/filePreview.ts index da62d2e689..e44376639a 100644 --- a/packages/shared/src/filePreview.ts +++ b/packages/shared/src/filePreview.ts @@ -10,6 +10,12 @@ export type FilePreviewKind = | "text" | "unsupported"; +export function isDownloadOnlyFile(path: string): boolean { + return /\.(apk|aab|ipa|exe|msi|dmg|iso|zip|tar|gz|bz2|xz|7z|rar|jar|war|dll|so|dylib|wasm|bin)$/i.test( + path, + ); +} + /** Content classification is identical for captured attachments and workspace references. */ export function filePreviewKind(file: { readonly name: string; diff --git a/scripts/build-fork-apk.sh b/scripts/build-fork-apk.sh old mode 100644 new mode 100755 diff --git a/scripts/publish-fork-apk.test.ts b/scripts/publish-fork-apk.test.ts index 4e639ef972..adabcdd616 100644 --- a/scripts/publish-fork-apk.test.ts +++ b/scripts/publish-fork-apk.test.ts @@ -65,6 +65,17 @@ describe("fork APK publishing", () => { } }); + it("passes a configured release body to the repository release", async () => { + const request = vi.fn().mockResolvedValue(new Response("{}")); + request.mockResolvedValueOnce(Response.json({ id: 123 })); + + await publishForkApk({ ...options, body: "Local release notes", request }); + + expect(JSON.parse(String(request.mock.calls[0]?.[1]?.body))).toMatchObject({ + body: "Local release notes", + }); + }); + it("does not publish an incomplete release after an upload failure", async () => { const request = vi .fn() diff --git a/scripts/publish-fork-apk.ts b/scripts/publish-fork-apk.ts index 6d58fbdbc6..5a7ed30c42 100644 --- a/scripts/publish-fork-apk.ts +++ b/scripts/publish-fork-apk.ts @@ -14,6 +14,7 @@ export async function publishForkApk(options: { apk: Blob; checksum: Blob; request?: typeof fetch; + body?: string; }) { const versionCode = parseAndroidApkReleaseTag(options.tag); const request = options.request ?? fetch; @@ -36,7 +37,9 @@ export async function publishForkApk(options: { tag_name: options.tag, target_commitish: options.commit, name: `Android APK · build ${versionCode}`, - body: "Download the APK below and open it on Android to install. This is a signed fork build; updates require the same signing key. The SHA-256 checksum is attached alongside the APK.", + body: + options.body ?? + "Download the APK below and open it on Android to install. This is a signed fork build; updates require the same signing key. The SHA-256 checksum is attached alongside the APK.", draft: true, prerelease: false, }), diff --git a/scripts/release-apk.sh b/scripts/release-apk.sh index 07ced66428..c2c160c4e3 100755 --- a/scripts/release-apk.sh +++ b/scripts/release-apk.sh @@ -1,75 +1,144 @@ -#!/usr/bin/env bash -set -euo pipefail +#!/bin/sh +# Build and publish the next t3code Android APK release. +# +# Without flags: build and publish the next APK version. +# With --dry-run: calculate and print the next version without building or publishing. +set -eu -cd "$(dirname "$0")/.." -CONFIG_FILE="${CONFIG_FILE:-.env.release}" -if [[ ! -f "$CONFIG_FILE" ]]; then - echo "Missing $CONFIG_FILE. Copy .env.release.example and fill it in." >&2 - exit 1 -fi -set -a -# shellcheck disable=SC1090 -source "$CONFIG_FILE" -set +a +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +DRY_RUN=0 -required=(T3CODE_APK_REPOSITORY_URL ANDROID_HOME ANDROID_NDK_HOME APK_KEYSTORE_BASE64 APK_KEYSTORE_PASSWORD APK_KEY_ALIAS APK_KEY_PASSWORD APK_RELEASE_TOKEN) -for name in "${required[@]}"; do - [[ -n "${!name:-}" ]] || { echo "$name must be set in $CONFIG_FILE" >&2; exit 1; } +for arg in "$@"; do + case "$arg" in + --dry-run) DRY_RUN=1 ;; + --help|-h) + printf '%s\n' 'Usage: ./scripts/release-apk.sh [--dry-run]' + printf '%s\n' ' (default) build and publish the next APK release' + printf '%s\n' ' --dry-run calculate and print the next version without building or publishing' + exit 0 + ;; + *) echo "Unknown option: $arg" >&2; exit 2 ;; + esac done -if ! git diff --quiet HEAD; then - echo "Working tree has changes. Commit them before releasing." >&2 - exit 1 +CONFIG_FILE=${CONFIG_FILE:-$ROOT/.env.release} +case "$CONFIG_FILE" in + /*) ;; + *) CONFIG_FILE="$ROOT/$CONFIG_FILE" ;; +esac +if [ -f "$CONFIG_FILE" ]; then + set -a + # shellcheck disable=SC1090 + . "$CONFIG_FILE" + set +a fi -highest=0 -while IFS= read -r tag; do - if [[ "$tag" =~ ^apk-([1-9][0-9]*)$ ]] && (( BASH_REMATCH[1] > highest )); then - highest=${BASH_REMATCH[1]} - fi -done < <(git ls-remote --tags --refs "$T3CODE_APK_REPOSITORY_URL" | sed 's#.*refs/tags/##') +API=${GITEA_API_URL:-https://git.molberg.cloud/api/v1/repos/alex/t3code} +REPOSITORY_URL=${T3CODE_APK_REPOSITORY_URL:-https://git.molberg.cloud/alex/t3code} +TOKEN=${APK_RELEASE_TOKEN:-${GITEA_TOKEN:-}} -if [[ -n "${APK_VERSION_CODE:-}" ]]; then - version_code="$APK_VERSION_CODE" +if [ "$DRY_RUN" -eq 0 ] && [ -z "$TOKEN" ]; then + echo "Set GITEA_TOKEN or APK_RELEASE_TOKEN in $CONFIG_FILE or the environment" >&2 + exit 2 +fi + +RELEASES_JSON=$(mktemp) +trap 'rm -f "$RELEASES_JSON"' EXIT HUP INT TERM + +if [ -n "$TOKEN" ]; then + curl -fsS -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36' \ + -H "Authorization: token $TOKEN" "$API/releases?limit=50" > "$RELEASES_JSON" else - version_code=$((highest + 1)) -fi -if ! [[ "$version_code" =~ ^[1-9][0-9]*$ ]] || (( version_code > 2100000000 )); then - echo "APK_VERSION_CODE must be between 1 and 2100000000." >&2 - exit 1 -fi -if (( version_code <= highest )); then - echo "Version code $version_code must exceed existing maximum $highest." >&2 - exit 1 + curl -fsS -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36' \ + "$API/releases?limit=50" > "$RELEASES_JSON" fi -tag_name="apk-$version_code" -if git ls-remote --exit-code --tags --refs origin "$tag_name" >/dev/null 2>&1; then - echo "Remote tag $tag_name already exists." >&2 - exit 1 -fi +VERSION_CODE=$(python3 - "$RELEASES_JSON" "${APK_VERSION_CODE:-}" <<'PY' +import json +import re +import sys -export T3CODE_APK_RELEASE_TAG="$tag_name" +path, override = sys.argv[1:] +if override: + print(override) + raise SystemExit + +highest = 0 +with open(path, encoding="utf-8") as handle: + for release in json.load(handle): + tag = str(release.get("tag_name", "")) + match = re.fullmatch(r"apk-([1-9][0-9]*)", tag) + if match: + highest = max(highest, int(match.group(1))) +print(highest + 1) +PY +) + +case "$VERSION_CODE" in + *[!0-9]*|'') echo "APK_VERSION_CODE must be a positive integer" >&2; exit 2 ;; +esac +[ "$VERSION_CODE" -gt 0 ] || { echo "APK_VERSION_CODE must be positive" >&2; exit 2; } +[ "$VERSION_CODE" -le 2100000000 ] || { echo "APK_VERSION_CODE must be at most 2100000000" >&2; exit 2; } + +TAG="apk-$VERSION_CODE" +VERSION_NAME=$(sed -n 's/.*version: "\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)".*/\1/p' "$ROOT/apps/mobile/app.config.ts" | head -n 1) +VERSION_NAME=${VERSION_NAME:-unknown} +printf 'Next APK release: %s (versionName %s)\n' "$TAG" "$VERSION_NAME" + +[ "$DRY_RUN" -eq 0 ] || exit 0 + +export T3CODE_APK_RELEASE_TAG="$TAG" +export T3CODE_APK_RELEASE_COMMIT=$(git -C "$ROOT" rev-parse HEAD) +export T3CODE_APK_REPOSITORY_URL="$REPOSITORY_URL" +export APK_RELEASE_TOKEN="$TOKEN" export APP_VARIANT=production export T3CODE_MOBILE_UPDATES_ENABLED=0 + +cd "$ROOT" bash scripts/build-fork-apk.sh -commit_sha=$(git rev-parse HEAD) -node --input-type=module <<'NODE' +APK="release/t3code-$TAG.apk" +CHECKSUM="$APK.sha256" +[ -s "$APK" ] || { echo "Build did not produce $APK" >&2; exit 1; } +[ -s "$CHECKSUM" ] || { echo "Build did not produce $CHECKSUM" >&2; exit 1; } + +sha256sum -c "$CHECKSUM" + +if [ -z "${APK_RELEASE_BODY:-}" ]; then + APK_RELEASE_BODY=$(python3 - "$TAG" "$VERSION_CODE" "$VERSION_NAME" "$T3CODE_APK_RELEASE_COMMIT" "$(sha256sum "$APK" | cut -d' ' -f1)" <<'PY' +import json +import sys + +print(json.dumps({ + "schema": 1, + "channel": "production", + "versionCode": int(sys.argv[2]), + "versionName": sys.argv[3], + "branch": "main", + "commit": sys.argv[4], + "sha256": sys.argv[5], +}, separators=(",", ":"))) +PY +) +fi + +APK_RELEASE_BODY="$APK_RELEASE_BODY" node --input-type=module <<'NODE' import * as NodeFS from "node:fs/promises"; import { publishForkApk } from "./scripts/publish-fork-apk.ts"; const tag = process.env.T3CODE_APK_RELEASE_TAG; const repositoryUrl = process.env.T3CODE_APK_REPOSITORY_URL; const token = process.env.APK_RELEASE_TOKEN; -const commit = process.env.APK_RELEASE_COMMIT; +const commit = process.env.T3CODE_APK_RELEASE_COMMIT; if (!tag || !repositoryUrl || !token || !commit) throw new Error("Release environment is incomplete."); await publishForkApk({ - tag, repositoryUrl, token, commit, + tag, + repositoryUrl, + token, + commit, + body: process.env.APK_RELEASE_BODY, apk: new Blob([await NodeFS.readFile(`release/t3code-${tag}.apk`)], { type: "application/vnd.android.package-archive" }), checksum: new Blob([await NodeFS.readFile(`release/t3code-${tag}.apk.sha256`)], { type: "text/plain" }), }); NODE -git tag "$tag_name" "$commit_sha" -git push origin "$tag_name" -echo "Published $tag_name" +printf 'Published %s\n' "$TAG"