Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0381ec7e53 | ||
|
|
8b5469863a | ||
|
|
58302b2010 | ||
|
|
1f2797325b | ||
|
|
c14a5ca492 | ||
|
|
eb733c10f2 | ||
|
|
8a02c71861 | ||
|
|
fdca15471d | ||
|
|
5d68fca8f2 | ||
|
|
2a33a18716 | ||
|
|
bde0a4c0dd | ||
|
|
54f167e2e0 | ||
|
|
d114e2772d | ||
|
|
0418301de7 | ||
|
|
5e8b2c800e | ||
|
|
b98233702c | ||
|
|
ecb35f7583 | ||
|
|
d359789ed4 | ||
|
|
462442667e | ||
|
|
c69120f484 | ||
|
|
7b928d5488 | ||
|
|
2fdc704bbb | ||
|
|
3513fa04fb |
No files matched your search
@@ -0,0 +1,134 @@
|
||||
name: Mobile Showcase Screenshots
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
platform:
|
||||
description: Device platforms to capture
|
||||
required: true
|
||||
default: all
|
||||
type: choice
|
||||
options:
|
||||
- all
|
||||
- ios
|
||||
- android
|
||||
appearance:
|
||||
description: System appearances to capture
|
||||
required: true
|
||||
default: both
|
||||
type: choice
|
||||
options:
|
||||
- both
|
||||
- dark
|
||||
- light
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
|
||||
jobs:
|
||||
ios:
|
||||
name: iPhone 6.9, iPhone 6.5, and iPad 13
|
||||
if: inputs.platform == 'all' || inputs.platform == 'ios'
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Capture iOS showcase
|
||||
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}"
|
||||
|
||||
- name: Validate App Store Connect assets
|
||||
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}" --validate-only
|
||||
|
||||
- name: Upload iOS screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: app-store-connect-screenshots
|
||||
path: artifacts/app-store/screenshots/apple/
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
android:
|
||||
name: Android phone, 7-inch tablet, and 10-inch tablet
|
||||
if: inputs.platform == 'all' || inputs.platform == 'android'
|
||||
runs-on: blacksmith-16vcpu-ubuntu-2404
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
T3_SHOWCASE_ANDROID_ABI: x86_64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
- name: Setup Gradle cache
|
||||
uses: gradle/actions/setup-gradle@v5
|
||||
|
||||
- name: Enable KVM
|
||||
run: |
|
||||
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS="static_node=kvm"' \
|
||||
| sudo tee /etc/udev/rules.d/99-kvm4all.rules
|
||||
sudo udevadm control --reload-rules
|
||||
sudo udevadm trigger --name-match=kvm
|
||||
|
||||
- name: Capture Android showcase
|
||||
uses: reactivecircus/android-emulator-runner@v2
|
||||
with:
|
||||
api-level: 36
|
||||
target: google_apis
|
||||
arch: x86_64
|
||||
profile: pixel_7_pro
|
||||
avd-name: Pixel_10_Pro
|
||||
cores: 8
|
||||
ram-size: 4096M
|
||||
disable-animations: false
|
||||
script: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}"
|
||||
|
||||
- name: Validate Google Play assets
|
||||
run: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}" --validate-only
|
||||
|
||||
- name: Upload Android screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: google-play-screenshots
|
||||
path: artifacts/app-store/screenshots/google-play/
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
@@ -27,6 +27,9 @@ squashfs-root/
|
||||
.gstack/
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
.showcase/
|
||||
apps/mobile/.showcase/
|
||||
artifacts/app-store/screenshots/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
|
||||
@@ -10,6 +10,7 @@ const { autoUpdaterMock } = vi.hoisted(() => ({
|
||||
autoInstallOnAppQuit: true,
|
||||
channel: "latest",
|
||||
disableDifferentialDownload: false,
|
||||
fullChangelog: false,
|
||||
checkForUpdates: vi.fn(() => Promise.resolve(null)),
|
||||
downloadUpdate: vi.fn(() => Promise.resolve([])),
|
||||
on: vi.fn(),
|
||||
@@ -33,6 +34,7 @@ describe("ElectronUpdater", () => {
|
||||
autoUpdaterMock.autoInstallOnAppQuit = true;
|
||||
autoUpdaterMock.channel = "latest";
|
||||
autoUpdaterMock.disableDifferentialDownload = false;
|
||||
autoUpdaterMock.fullChangelog = false;
|
||||
autoUpdaterMock.checkForUpdates.mockClear();
|
||||
autoUpdaterMock.checkForUpdates.mockImplementation(() => Promise.resolve(null));
|
||||
autoUpdaterMock.downloadUpdate.mockClear();
|
||||
@@ -98,6 +100,18 @@ describe("ElectronUpdater", () => {
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
|
||||
it.effect("sets full changelog mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const updater = yield* ElectronUpdater.ElectronUpdater;
|
||||
|
||||
yield* updater.setFullChangelog(true);
|
||||
assert.equal(autoUpdaterMock.fullChangelog, true);
|
||||
|
||||
yield* updater.setFullChangelog(false);
|
||||
assert.equal(autoUpdaterMock.fullChangelog, false);
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves quit-and-install flags and the execution-time channel", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("quit and install failed");
|
||||
|
||||
@@ -66,6 +66,7 @@ export class ElectronUpdater extends Context.Service<
|
||||
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
|
||||
readonly allowDowngrade: Effect.Effect<boolean>;
|
||||
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setFullChangelog: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
|
||||
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
|
||||
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
|
||||
@@ -112,6 +113,11 @@ export const make = ElectronUpdater.of({
|
||||
autoUpdater.allowDowngrade = value;
|
||||
return Effect.void;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.suspend(() => {
|
||||
autoUpdater.fullChangelog = value;
|
||||
return Effect.void;
|
||||
}),
|
||||
setDisableDifferentialDownload: (value) =>
|
||||
Effect.suspend(() => {
|
||||
autoUpdater.disableDifferentialDownload = value;
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBootstraps,
|
||||
getLocalEnvironmentBearerToken,
|
||||
getWindowFullscreenState,
|
||||
openExternal,
|
||||
pickFolder,
|
||||
setTheme,
|
||||
@@ -48,6 +49,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* PreviewIpc.installPreviewEventForwarding();
|
||||
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getWindowFullscreenState);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
|
||||
yield* ipc.handle(getLocalEnvironmentBearerToken);
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ export const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
|
||||
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
|
||||
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
export const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
|
||||
import { getLocalEnvironmentBootstraps } from "./window.ts";
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import { getLocalEnvironmentBootstraps, getWindowFullscreenState } from "./window.ts";
|
||||
|
||||
const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "wsl.exe",
|
||||
@@ -126,3 +130,19 @@ describe("getLocalEnvironmentBootstraps", () => {
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));
|
||||
});
|
||||
});
|
||||
|
||||
describe("getWindowFullscreenState", () => {
|
||||
it.effect("reads the current native window state", () => {
|
||||
const window = { isFullScreen: () => true } as Electron.BrowserWindow;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
assert.isTrue(yield* getWindowFullscreenState.handler());
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mock(ElectronWindow.ElectronWindow)({
|
||||
currentMainOrFirst: Effect.succeed(Option.some(window)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -55,6 +55,16 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const window = yield* electronWindow.currentMainOrFirst;
|
||||
return Option.isSome(window) && window.value.isFullScreen();
|
||||
}),
|
||||
});
|
||||
|
||||
export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
|
||||
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
|
||||
|
||||
@@ -116,6 +116,19 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getWindowFullscreenState: () =>
|
||||
ipcRenderer.sendSync(IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL) === true,
|
||||
onWindowFullscreenStateChange: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, fullscreen: unknown) => {
|
||||
if (typeof fullscreen !== "boolean") return;
|
||||
listener(fullscreen);
|
||||
};
|
||||
|
||||
ipcRenderer.on(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getUpdateState: () => ipcRenderer.invoke(IpcChannels.UPDATE_GET_STATE_CHANNEL),
|
||||
setUpdateChannel: (channel) =>
|
||||
ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, channel),
|
||||
|
||||
@@ -38,6 +38,7 @@ const flushCallbacks = Effect.yieldNow;
|
||||
function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
let checkCount = 0;
|
||||
let allowDowngrade = false;
|
||||
let fullChangelog = false;
|
||||
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
|
||||
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
|
||||
const sentStates: DesktopUpdateState[] = [];
|
||||
@@ -73,6 +74,10 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
Effect.sync(() => {
|
||||
allowDowngrade = value;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.sync(() => {
|
||||
fullChangelog = value;
|
||||
}),
|
||||
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
|
||||
checkForUpdates: Effect.sync(() => {
|
||||
checkCount += 1;
|
||||
@@ -186,6 +191,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
layer,
|
||||
checkCount: () => checkCount,
|
||||
feedUrls: () => feedUrls,
|
||||
fullChangelog: () => fullChangelog,
|
||||
listenerCount: () =>
|
||||
Array.from(listeners.values()).reduce(
|
||||
(total, eventListeners) => total + eventListeners.size,
|
||||
@@ -287,6 +293,49 @@ describe("DesktopUpdates", () => {
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("enables nightly full changelog release notes and broadcasts summaries", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
|
||||
yield* updates.setChannel("nightly");
|
||||
assert.equal(harness.fullChangelog(), true);
|
||||
|
||||
harness.emit("update-available", {
|
||||
version: "1.2.4-nightly.20260709.766",
|
||||
releaseNotes: [
|
||||
{
|
||||
version: "1.2.4-nightly.20260709.766",
|
||||
note: `<h2>What's Changed</h2><ul><li>feat(client): persist offline environment data by <a>@juliusmarminge</a> in <a>#3795</a></li></ul><h2>Full Changelog</h2>`,
|
||||
},
|
||||
{
|
||||
version: "1.2.4-nightly.20260709.765",
|
||||
note: "- [codex] Upgrade Clerk stack by @juliusmarminge in #3821",
|
||||
},
|
||||
],
|
||||
});
|
||||
yield* flushCallbacks;
|
||||
|
||||
const state = yield* updates.getState;
|
||||
assert.equal(state.status, "available");
|
||||
assert.deepEqual(state.releaseNotes, [
|
||||
{
|
||||
version: "1.2.4-nightly.20260709.766",
|
||||
items: ["feat(client): persist offline environment data by @juliusmarminge in #3795"],
|
||||
},
|
||||
{
|
||||
version: "1.2.4-nightly.20260709.765",
|
||||
items: ["[codex] Upgrade Clerk stack by @juliusmarminge in #3821"],
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(harness.sentStates.at(-1)?.releaseNotes, state.releaseNotes);
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("keeps raw updater event failures out of update state", () => {
|
||||
const harness = makeHarness();
|
||||
const cause = new Error(
|
||||
|
||||
@@ -27,6 +27,7 @@ import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
|
||||
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
@@ -49,6 +50,10 @@ type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type;
|
||||
|
||||
const UpdateInfo = Schema.Struct({
|
||||
version: Schema.String,
|
||||
// Left unvalidated on purpose: a malformed release-notes payload must never
|
||||
// fail the decode and block the update state transition. The shape is
|
||||
// validated defensively in normalizeDesktopUpdateReleaseNotes.
|
||||
releaseNotes: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
const DownloadProgressInfo = Schema.Struct({
|
||||
@@ -330,10 +335,12 @@ export const make = Effect.gen(function* () {
|
||||
yield* electronUpdater.setChannel(channel);
|
||||
yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
|
||||
yield* electronUpdater.setAllowDowngrade(allowsPrerelease);
|
||||
yield* electronUpdater.setFullChangelog(allowsPrerelease);
|
||||
yield* logUpdaterInfo("using update channel", {
|
||||
channel,
|
||||
allowPrerelease: allowsPrerelease,
|
||||
allowDowngrade: allowsPrerelease,
|
||||
fullChangelog: allowsPrerelease,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -567,11 +574,15 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const checkedAt = yield* currentIsoTimestamp;
|
||||
const releaseNotes = normalizeDesktopUpdateReleaseNotes(info.releaseNotes, info.version);
|
||||
yield* setState(
|
||||
reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt),
|
||||
reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt, releaseNotes),
|
||||
);
|
||||
yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
|
||||
yield* logUpdaterInfo("update available", { version: info.version });
|
||||
yield* logUpdaterInfo("update available", {
|
||||
version: info.version,
|
||||
releaseNoteGroups: releaseNotes.length,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
|
||||
|
||||
describe("normalizeDesktopUpdateReleaseNotes", () => {
|
||||
it("splits a plain string note into items under the fallback version", () => {
|
||||
const notes = normalizeDesktopUpdateReleaseNotes(
|
||||
"## What's changed\n- First fix\n- Second fix",
|
||||
"1.2.3",
|
||||
);
|
||||
expect(notes).toEqual([{ version: "1.2.3", items: ["First fix", "Second fix"] }]);
|
||||
});
|
||||
|
||||
it("keeps per-version groups and drops empty ones", () => {
|
||||
const notes = normalizeDesktopUpdateReleaseNotes(
|
||||
[
|
||||
{ version: "1.2.3", note: "- Newer change" },
|
||||
{ version: "1.2.2", note: "Full changelog: https://example.com/compare/x...y" },
|
||||
{ version: "1.2.1", note: "- Older change" },
|
||||
],
|
||||
"1.2.3",
|
||||
);
|
||||
expect(notes).toEqual([
|
||||
{ version: "1.2.3", items: ["Newer change"] },
|
||||
{ version: "1.2.1", items: ["Older change"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("decodes valid HTML entities", () => {
|
||||
const notes = normalizeDesktopUpdateReleaseNotes("- Fix & polish 😀", "1.0.0");
|
||||
expect(notes).toEqual([{ version: "1.0.0", items: ["Fix & polish 😀"] }]);
|
||||
});
|
||||
|
||||
it("ignores malformed entries instead of throwing", () => {
|
||||
const notes = normalizeDesktopUpdateReleaseNotes(
|
||||
[
|
||||
{ version: "1.2.3", note: "- Valid change" },
|
||||
{ version: 42, note: "- Bad version type" },
|
||||
{ version: "1.2.1", note: { html: "<p>object note</p>" } },
|
||||
"not an object",
|
||||
null,
|
||||
],
|
||||
"1.2.3",
|
||||
);
|
||||
expect(notes).toEqual([{ version: "1.2.3", items: ["Valid change"] }]);
|
||||
});
|
||||
|
||||
it("returns non-empty groups even when preceded by many boilerplate-only groups", () => {
|
||||
const boilerplate = Array.from({ length: 7 }, (_, index) => ({
|
||||
version: `1.3.${9 - index}`,
|
||||
note: "Full changelog: https://example.com/compare/x...y",
|
||||
}));
|
||||
const notes = normalizeDesktopUpdateReleaseNotes(
|
||||
[...boilerplate, { version: "1.3.2", note: "- Older but real change" }],
|
||||
"1.3.9",
|
||||
);
|
||||
expect(notes).toEqual([{ version: "1.3.2", items: ["Older but real change"] }]);
|
||||
});
|
||||
|
||||
it("does not throw on out-of-range numeric entities and keeps the literal", () => {
|
||||
expect(() =>
|
||||
normalizeDesktopUpdateReleaseNotes("- Broken entity �", "1.0.0"),
|
||||
).not.toThrow();
|
||||
const notes = normalizeDesktopUpdateReleaseNotes("- Broken entity �", "1.0.0");
|
||||
expect(notes).toEqual([{ version: "1.0.0", items: ["Broken entity �"] }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import type { DesktopUpdateReleaseNote } from "@t3tools/contracts";
|
||||
|
||||
interface ElectronReleaseNoteInfo {
|
||||
readonly version: string;
|
||||
readonly note: string | null | undefined;
|
||||
}
|
||||
|
||||
function isElectronReleaseNoteInfo(value: unknown): value is ElectronReleaseNoteInfo {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const candidate = value as { readonly version?: unknown; readonly note?: unknown };
|
||||
return (
|
||||
typeof candidate.version === "string" &&
|
||||
(typeof candidate.note === "string" || candidate.note === null || candidate.note === undefined)
|
||||
);
|
||||
}
|
||||
|
||||
const MAX_RELEASE_NOTE_GROUPS = 6;
|
||||
const MAX_RELEASE_NOTE_ITEMS_PER_GROUP = 8;
|
||||
const MAX_RELEASE_NOTE_ITEM_LENGTH = 220;
|
||||
|
||||
const HTML_ENTITY_REPLACEMENTS: Readonly<Record<string, string>> = {
|
||||
amp: "&",
|
||||
apos: "'",
|
||||
gt: ">",
|
||||
lt: "<",
|
||||
nbsp: " ",
|
||||
quot: '"',
|
||||
};
|
||||
|
||||
function decodeCodePoint(codePoint: number, entity: string): string {
|
||||
// String.fromCodePoint throws RangeError outside the valid Unicode range, and
|
||||
// Number.isFinite alone lets oversized values (e.g. �) through.
|
||||
if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
|
||||
return `&${entity};`;
|
||||
}
|
||||
return String.fromCodePoint(codePoint);
|
||||
}
|
||||
|
||||
function decodeHtmlEntity(entity: string): string {
|
||||
const named = HTML_ENTITY_REPLACEMENTS[entity];
|
||||
if (named) return named;
|
||||
if (entity.startsWith("#x")) {
|
||||
return decodeCodePoint(Number.parseInt(entity.slice(2), 16), entity);
|
||||
}
|
||||
if (entity.startsWith("#")) {
|
||||
return decodeCodePoint(Number.parseInt(entity.slice(1), 10), entity);
|
||||
}
|
||||
return `&${entity};`;
|
||||
}
|
||||
|
||||
function decodeHtmlEntities(input: string): string {
|
||||
return input.replace(/&([a-zA-Z]+|#\d+|#x[0-9a-fA-F]+);/g, (_, entity: string) =>
|
||||
decodeHtmlEntity(entity),
|
||||
);
|
||||
}
|
||||
|
||||
function stripMarkup(input: string): string {
|
||||
return decodeHtmlEntities(
|
||||
input
|
||||
.replace(/<br\s*\/?>/gi, "\n")
|
||||
.replace(/<li\b[^>]*>/gi, "\n- ")
|
||||
.replace(/<\/(?:p|div|li|h[1-6]|ul|ol|blockquote)>/gi, "\n")
|
||||
.replace(/<[^>]*>/g, "")
|
||||
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
|
||||
.replace(/\*\*([^*]+)\*\*/g, "$1"),
|
||||
);
|
||||
}
|
||||
|
||||
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()}...`;
|
||||
}
|
||||
|
||||
function isIgnoredReleaseNoteLine(line: string): boolean {
|
||||
const normalized = line
|
||||
.toLowerCase()
|
||||
.replace(/[*_`#]/g, "")
|
||||
.trim();
|
||||
return (
|
||||
normalized === "" ||
|
||||
normalized === "what's changed" ||
|
||||
normalized === "whats changed" ||
|
||||
normalized === "full changelog" ||
|
||||
normalized === "new contributors" ||
|
||||
normalized.startsWith("compare: ") ||
|
||||
normalized.includes("/compare/")
|
||||
);
|
||||
}
|
||||
|
||||
function extractReleaseNoteItems(note: string | null | undefined): ReadonlyArray<string> {
|
||||
if (!note) return [];
|
||||
|
||||
const items: string[] = [];
|
||||
for (const rawLine of stripMarkup(note).split("\n")) {
|
||||
const item = rawLine
|
||||
.trim()
|
||||
.replace(/^[-*]\s+/, "")
|
||||
.replace(/^\d+[.)]\s+/, "")
|
||||
.replace(/\s+/g, " ");
|
||||
if (isIgnoredReleaseNoteLine(item)) continue;
|
||||
items.push(truncateReleaseNoteItem(item));
|
||||
if (items.length >= MAX_RELEASE_NOTE_ITEMS_PER_GROUP) break;
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
export function normalizeDesktopUpdateReleaseNotes(
|
||||
releaseNotes: unknown,
|
||||
fallbackVersion: string,
|
||||
): ReadonlyArray<DesktopUpdateReleaseNote> {
|
||||
const rawNotes =
|
||||
typeof releaseNotes === "string"
|
||||
? [{ version: fallbackVersion, note: releaseNotes }]
|
||||
: Array.isArray(releaseNotes)
|
||||
? releaseNotes.filter(isElectronReleaseNoteInfo)
|
||||
: [];
|
||||
|
||||
return rawNotes
|
||||
.map((entry) => ({
|
||||
version: entry.version,
|
||||
items: extractReleaseNoteItems(entry.note),
|
||||
}))
|
||||
.filter((entry) => entry.items.length > 0)
|
||||
.slice(0, MAX_RELEASE_NOTE_GROUPS);
|
||||
}
|
||||
@@ -118,6 +118,12 @@ describe("updateMachine", () => {
|
||||
});
|
||||
|
||||
it("tracks available, download start, and progress cleanly", () => {
|
||||
const releaseNotes = [
|
||||
{
|
||||
version: "1.1.0",
|
||||
items: ["feat: add update release notes"],
|
||||
},
|
||||
];
|
||||
const available = reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
@@ -126,15 +132,33 @@ describe("updateMachine", () => {
|
||||
},
|
||||
"1.1.0",
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
releaseNotes,
|
||||
);
|
||||
const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
|
||||
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
|
||||
|
||||
expect(available.status).toBe("available");
|
||||
expect(available.channel).toBe("latest");
|
||||
expect(available.releaseNotes).toBe(releaseNotes);
|
||||
expect(downloading.releaseNotes).toBe(releaseNotes);
|
||||
expect(downloading.status).toBe("downloading");
|
||||
expect(downloading.downloadPercent).toBe(0);
|
||||
expect(progress.downloadPercent).toBe(55.5);
|
||||
expect(progress.errorContext).toBeNull();
|
||||
});
|
||||
|
||||
it("clears release notes when checking again", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckStart(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "nightly"),
|
||||
enabled: true,
|
||||
status: "available",
|
||||
availableVersion: "1.1.0-nightly.1",
|
||||
releaseNotes: [{ version: "1.1.0-nightly.1", items: ["feat: old note"] }],
|
||||
},
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.releaseNotes).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {
|
||||
DesktopRuntimeInfo,
|
||||
DesktopUpdateChannel,
|
||||
DesktopUpdateReleaseNote,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
@@ -29,6 +30,7 @@ export function createInitialDesktopUpdateState(
|
||||
runningUnderArm64Translation: runtimeInfo.runningUnderArm64Translation,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
@@ -45,6 +47,7 @@ export function reduceDesktopUpdateStateOnCheckStart(
|
||||
...state,
|
||||
status: "checking",
|
||||
checkedAt,
|
||||
releaseNotes: [],
|
||||
message: null,
|
||||
downloadPercent: null,
|
||||
errorContext: null,
|
||||
@@ -72,12 +75,14 @@ export function reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
state: DesktopUpdateState,
|
||||
version: string,
|
||||
checkedAt: string,
|
||||
releaseNotes: ReadonlyArray<DesktopUpdateReleaseNote> = [],
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "available",
|
||||
availableVersion: version,
|
||||
downloadedVersion: null,
|
||||
releaseNotes,
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
@@ -95,6 +100,7 @@ export function reduceDesktopUpdateStateOnNoUpdate(
|
||||
status: "up-to-date",
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
|
||||
@@ -28,7 +28,7 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
|
||||
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopWindow from "./DesktopWindow.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
@@ -46,6 +46,7 @@ const environmentInput = {
|
||||
} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
|
||||
|
||||
function makeFakeBrowserWindow() {
|
||||
const windowListeners = new Map<string, (...args: readonly unknown[]) => void>();
|
||||
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
|
||||
const webContents = {
|
||||
copyImageAt: vi.fn(),
|
||||
@@ -66,10 +67,13 @@ function makeFakeBrowserWindow() {
|
||||
close: vi.fn(),
|
||||
focus: vi.fn(),
|
||||
isDestroyed: vi.fn(() => false),
|
||||
isFullScreen: vi.fn(() => false),
|
||||
isMinimized: vi.fn(() => false),
|
||||
isVisible: vi.fn(() => true),
|
||||
loadURL: vi.fn(() => Promise.resolve()),
|
||||
on: vi.fn(),
|
||||
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
windowListeners.set(eventName, listener);
|
||||
}),
|
||||
once: vi.fn(),
|
||||
restore: vi.fn(),
|
||||
setBackgroundColor: vi.fn(),
|
||||
@@ -88,6 +92,7 @@ function makeFakeBrowserWindow() {
|
||||
send: webContents.send,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
windowListeners,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -338,6 +343,37 @@ describe("DesktopWindow", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("publishes native macOS fullscreen changes to the renderer", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const enterFullscreen = fakeWindow.windowListeners.get("enter-full-screen");
|
||||
const leaveFullscreen = fakeWindow.windowListeners.get("leave-full-screen");
|
||||
if (!enterFullscreen || !leaveFullscreen) {
|
||||
return yield* Effect.die("fullscreen listeners were not registered");
|
||||
}
|
||||
|
||||
enterFullscreen();
|
||||
leaveFullscreen();
|
||||
assert.deepEqual(fakeWindow.send.mock.calls, [
|
||||
[WINDOW_FULLSCREEN_STATE_CHANNEL, true],
|
||||
[WINDOW_FULLSCREEN_STATE_CHANNEL, false],
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers when the development renderer is temporarily unreachable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
|
||||
@@ -15,7 +15,7 @@ import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
|
||||
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
@@ -365,6 +365,15 @@ export const make = Effect.gen(function* () {
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
|
||||
if (environment.platform === "darwin") {
|
||||
window.on("enter-full-screen", () => {
|
||||
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
|
||||
});
|
||||
window.on("leave-full-screen", () => {
|
||||
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
|
||||
});
|
||||
}
|
||||
|
||||
let developmentLoadRetryIndex = 0;
|
||||
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
|
||||
const clearDevelopmentLoadRetry = () => {
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
|
||||
interface Props {
|
||||
readonly title: string;
|
||||
readonly description: string;
|
||||
readonly heading: string;
|
||||
readonly lede: string;
|
||||
readonly effectiveDate: string;
|
||||
readonly lastUpdated: string;
|
||||
readonly sections: ReadonlyArray<readonly [id: string, label: string]>;
|
||||
}
|
||||
|
||||
const { title, description, heading, lede, effectiveDate, lastUpdated, sections } = Astro.props;
|
||||
---
|
||||
|
||||
<Layout title={title} description={description} pageClass="legal-document-page">
|
||||
<div class="legal-page">
|
||||
<a class="legal-index-link" href="/legal"><span aria-hidden="true">←</span> All legal documents</a>
|
||||
<header class="legal-hero">
|
||||
<p class="eyebrow">T3 Tools, Inc. / Legal</p>
|
||||
<h1>{heading}</h1>
|
||||
<p class="legal-lede">{lede}</p>
|
||||
<dl class="legal-dates" aria-label="Document dates">
|
||||
<div>
|
||||
<dt>Effective Date</dt>
|
||||
<dd>{effectiveDate}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Last Updated</dt>
|
||||
<dd>{lastUpdated}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</header>
|
||||
|
||||
<div class="legal-rule" aria-hidden="true"></div>
|
||||
|
||||
<div class="legal-layout">
|
||||
<aside class="legal-nav" aria-label="On this page">
|
||||
<p class="legal-nav-label">On this page</p>
|
||||
<ol>
|
||||
{sections.map(([id, label], index) => (
|
||||
<li>
|
||||
<a href={`#${id}`} data-legal-nav-link={id}>
|
||||
<span>{String(index + 1).padStart(2, "0")}</span>
|
||||
{label}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</aside>
|
||||
|
||||
<article class="legal-copy">
|
||||
<slot />
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
|
||||
<script>
|
||||
const navLinks = Array.from(
|
||||
document.querySelectorAll<HTMLAnchorElement>("[data-legal-nav-link]"),
|
||||
);
|
||||
const sections = navLinks
|
||||
.map((link) => {
|
||||
const id = link.dataset.legalNavLink;
|
||||
const section = id ? document.getElementById(id) : null;
|
||||
return section ? { link, section } : null;
|
||||
})
|
||||
.filter((entry): entry is { link: HTMLAnchorElement; section: HTMLElement } => entry !== null);
|
||||
|
||||
let activeId = "";
|
||||
let frame = 0;
|
||||
|
||||
const updateActiveSection = () => {
|
||||
frame = 0;
|
||||
const marker = Math.min(180, window.innerHeight * 0.28);
|
||||
let active = sections[0];
|
||||
|
||||
for (const entry of sections) {
|
||||
if (entry.section.getBoundingClientRect().top > marker) break;
|
||||
active = entry;
|
||||
}
|
||||
|
||||
if (window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 2) {
|
||||
active = sections[sections.length - 1];
|
||||
}
|
||||
|
||||
if (!active || active.section.id === activeId) return;
|
||||
activeId = active.section.id;
|
||||
|
||||
for (const { link, section } of sections) {
|
||||
if (section.id === activeId) {
|
||||
link.setAttribute("aria-current", "location");
|
||||
} else {
|
||||
link.removeAttribute("aria-current");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const scheduleUpdate = () => {
|
||||
if (frame) return;
|
||||
frame = window.requestAnimationFrame(updateActiveSection);
|
||||
};
|
||||
|
||||
updateActiveSection();
|
||||
window.addEventListener("scroll", scheduleUpdate, { passive: true });
|
||||
window.addEventListener("resize", scheduleUpdate);
|
||||
</script>
|
||||
|
||||
<style is:global>
|
||||
.legal-page {
|
||||
width: min(1120px, calc(100% - 64px));
|
||||
margin: 0 auto;
|
||||
padding: clamp(72px, 10vw, 132px) 0 112px;
|
||||
}
|
||||
|
||||
.legal-index-link {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.legal-hero {
|
||||
max-width: 820px;
|
||||
animation: fade-in 0.8s ease-out both;
|
||||
}
|
||||
|
||||
.legal-hero h1 {
|
||||
margin-top: 18px;
|
||||
font-size: clamp(3.4rem, 8vw, 7.4rem);
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.02em;
|
||||
line-height: 0.9;
|
||||
}
|
||||
|
||||
.legal-lede {
|
||||
max-width: 720px;
|
||||
margin-top: 34px;
|
||||
color: var(--fg-muted);
|
||||
font-size: clamp(1.05rem, 1.8vw, 1.3rem);
|
||||
line-height: 1.65;
|
||||
letter-spacing: -0.012em;
|
||||
}
|
||||
|
||||
.legal-dates {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 36px;
|
||||
margin-top: 38px;
|
||||
}
|
||||
|
||||
.legal-dates div {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.legal-dates dt,
|
||||
.legal-nav-label,
|
||||
.section-number {
|
||||
color: var(--fg-dim);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.68rem;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.12em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.legal-dates dd {
|
||||
color: var(--fg);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.legal-rule {
|
||||
height: 1px;
|
||||
margin: 72px 0;
|
||||
background: linear-gradient(90deg, var(--border-strong), var(--border) 65%, transparent);
|
||||
}
|
||||
|
||||
.legal-layout {
|
||||
display: grid;
|
||||
grid-template-columns: 210px minmax(0, 720px);
|
||||
gap: clamp(64px, 10vw, 140px);
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.legal-nav {
|
||||
position: sticky;
|
||||
top: 88px;
|
||||
max-height: calc(100vh - 112px);
|
||||
overflow-y: auto;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.legal-nav ol {
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
margin-top: 16px;
|
||||
padding-bottom: 12px;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.legal-nav a {
|
||||
display: grid;
|
||||
grid-template-columns: 24px 1fr;
|
||||
gap: 9px;
|
||||
margin-left: -10px;
|
||||
padding: 7px 8px 7px 10px;
|
||||
border-radius: 6px;
|
||||
color: var(--fg-dim);
|
||||
font-size: 0.78rem;
|
||||
line-height: 1.35;
|
||||
transition:
|
||||
color 0.16s ease,
|
||||
background-color 0.16s ease,
|
||||
box-shadow 0.16s ease;
|
||||
}
|
||||
|
||||
.legal-nav a span {
|
||||
color: var(--fg-faint);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.64rem;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.legal-nav a:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
.legal-nav a[aria-current="location"] {
|
||||
color: var(--fg);
|
||||
background: color-mix(in srgb, var(--accent) 8%, transparent);
|
||||
box-shadow: inset 2px 0 var(--accent);
|
||||
}
|
||||
|
||||
.legal-nav a[aria-current="location"] span {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.legal-copy {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.legal-copy section {
|
||||
scroll-margin-top: 104px;
|
||||
}
|
||||
|
||||
.legal-copy section + section {
|
||||
margin-top: 82px;
|
||||
padding-top: 82px;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.section-number {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.legal-copy h2 {
|
||||
margin: 8px 0 28px;
|
||||
color: var(--fg);
|
||||
font-size: clamp(1.75rem, 3vw, 2.45rem);
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.04em;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.legal-copy h3 {
|
||||
margin: 32px 0 10px;
|
||||
color: var(--fg);
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.015em;
|
||||
}
|
||||
|
||||
.legal-copy h4 {
|
||||
margin: 24px 0 8px;
|
||||
color: var(--fg);
|
||||
font-size: 0.94rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.legal-copy p,
|
||||
.legal-copy li,
|
||||
.legal-copy address {
|
||||
color: var(--fg-muted);
|
||||
font-size: 0.98rem;
|
||||
font-style: normal;
|
||||
line-height: 1.78;
|
||||
}
|
||||
|
||||
.legal-copy p + p {
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.legal-copy strong {
|
||||
color: var(--fg);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.legal-copy ul,
|
||||
.legal-copy ol {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
margin: 18px 0 20px;
|
||||
padding-left: 1.2rem;
|
||||
}
|
||||
|
||||
.legal-copy li {
|
||||
padding-left: 7px;
|
||||
}
|
||||
|
||||
.legal-copy li::marker {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.legal-copy .provider-list {
|
||||
gap: 28px;
|
||||
}
|
||||
|
||||
.provider-list a,
|
||||
.legal-copy a {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.legal-copy a {
|
||||
color: var(--fg);
|
||||
text-decoration: underline;
|
||||
text-decoration-color: color-mix(in srgb, var(--accent) 55%, transparent);
|
||||
text-underline-offset: 4px;
|
||||
transition: text-decoration-color 0.16s ease;
|
||||
}
|
||||
|
||||
.legal-copy a:hover {
|
||||
text-decoration-color: var(--accent);
|
||||
}
|
||||
|
||||
.legal-notice {
|
||||
color: var(--fg) !important;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.legal-copy address {
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.contact-link {
|
||||
display: inline-block;
|
||||
margin-top: 18px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
@media (max-width: 820px) {
|
||||
.legal-index-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 38px;
|
||||
color: var(--fg-dim);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.72rem;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.legal-page {
|
||||
width: min(100% - 40px, 720px);
|
||||
padding-top: 56px;
|
||||
padding-bottom: 80px;
|
||||
}
|
||||
|
||||
.legal-hero h1 {
|
||||
font-size: clamp(3.1rem, 16vw, 5rem);
|
||||
}
|
||||
|
||||
.legal-rule {
|
||||
margin: 52px 0;
|
||||
}
|
||||
|
||||
.legal-layout {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.legal-nav {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.legal-copy section + section {
|
||||
margin-top: 62px;
|
||||
padding-top: 62px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.legal-page {
|
||||
width: calc(100% - 32px);
|
||||
padding-top: 42px;
|
||||
}
|
||||
|
||||
.legal-lede {
|
||||
margin-top: 26px;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.legal-dates {
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.legal-copy p,
|
||||
.legal-copy li,
|
||||
.legal-copy address {
|
||||
font-size: 0.94rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -4,11 +4,13 @@ import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
|
||||
interface Props {
|
||||
title?: string;
|
||||
description?: string;
|
||||
pageClass?: string;
|
||||
}
|
||||
|
||||
const {
|
||||
title = "T3 Code",
|
||||
description = "T3 Code — The open-source control plane for coding agents.",
|
||||
pageClass,
|
||||
} = Astro.props;
|
||||
---
|
||||
|
||||
@@ -30,7 +32,7 @@ const {
|
||||
<title>{title}</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<div class:list={["page", pageClass]}>
|
||||
<nav class="nav">
|
||||
<div class="nav-inner">
|
||||
<a href="/" class="nav-brand" aria-label="T3 Code home">
|
||||
@@ -67,6 +69,9 @@ const {
|
||||
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
|
||||
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
|
||||
<a href="/download">Download</a>
|
||||
<a href="/terms-of-service">Terms</a>
|
||||
<a href="/privacy-policy">Privacy</a>
|
||||
<a href="/security-policy">Security</a>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
@@ -279,7 +284,7 @@ const {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow-x: hidden;
|
||||
overflow-x: clip;
|
||||
}
|
||||
|
||||
.nav {
|
||||
@@ -402,6 +407,8 @@ const {
|
||||
|
||||
.footer-links {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
@@ -421,6 +428,28 @@ const {
|
||||
padding-left: 20px;
|
||||
padding-right: 20px;
|
||||
}
|
||||
|
||||
.legal-document-page .nav {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.footer {
|
||||
padding-bottom: max(32px, env(safe-area-inset-bottom));
|
||||
}
|
||||
|
||||
.footer-inner {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
gap: 28px;
|
||||
}
|
||||
|
||||
.footer-links {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
width: 100%;
|
||||
gap: 14px 20px;
|
||||
justify-content: initial;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
|
||||
const documents = [
|
||||
{
|
||||
number: "01",
|
||||
title: "Privacy Policy",
|
||||
description: "How T3 Code handles information, connected services, and your privacy choices.",
|
||||
href: "/privacy-policy",
|
||||
},
|
||||
{
|
||||
number: "02",
|
||||
title: "Terms of Service",
|
||||
description: "The terms that govern your use of T3 Code and T3 Tools-operated services.",
|
||||
href: "/terms-of-service",
|
||||
},
|
||||
{
|
||||
number: "03",
|
||||
title: "Security Policy",
|
||||
description: "Our security practices, responsible disclosure process, and shared responsibilities.",
|
||||
href: "/security-policy",
|
||||
},
|
||||
] as const;
|
||||
---
|
||||
|
||||
<Layout
|
||||
title="Legal — T3 Code"
|
||||
description="Privacy, terms, and security documents for T3 Code."
|
||||
pageClass="legal-document-page"
|
||||
>
|
||||
<div class="legal-index">
|
||||
<header class="legal-index-hero">
|
||||
<p class="eyebrow">T3 Tools, Inc. / Legal</p>
|
||||
<h1>Legal</h1>
|
||||
<p>Policies and terms for T3 Code, collected in one place.</p>
|
||||
</header>
|
||||
|
||||
<nav class="document-list" aria-label="Legal documents">
|
||||
{documents.map((document) => (
|
||||
<a href={document.href} class="document-card">
|
||||
<span class="document-number">{document.number}</span>
|
||||
<span class="document-copy">
|
||||
<strong>{document.title}</strong>
|
||||
<span>{document.description}</span>
|
||||
</span>
|
||||
<span class="document-arrow" aria-hidden="true">↗</span>
|
||||
</a>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
</Layout>
|
||||
|
||||
<style>
|
||||
.legal-index {
|
||||
width: min(960px, calc(100% - 64px));
|
||||
margin: 0 auto;
|
||||
padding: clamp(72px, 10vw, 132px) 0 112px;
|
||||
}
|
||||
|
||||
.legal-index-hero {
|
||||
max-width: 680px;
|
||||
animation: fade-in 0.7s ease-out both;
|
||||
}
|
||||
|
||||
.legal-index h1 {
|
||||
margin-top: 18px;
|
||||
font-size: clamp(4rem, 10vw, 7.4rem);
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.04em;
|
||||
line-height: 0.9;
|
||||
}
|
||||
|
||||
.legal-index-hero > p:last-child {
|
||||
margin-top: 30px;
|
||||
color: var(--fg-muted);
|
||||
font-size: clamp(1.05rem, 2vw, 1.3rem);
|
||||
line-height: 1.65;
|
||||
}
|
||||
|
||||
.document-list {
|
||||
display: grid;
|
||||
margin-top: clamp(64px, 9vw, 96px);
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.document-card {
|
||||
display: grid;
|
||||
grid-template-columns: 42px minmax(0, 1fr) auto;
|
||||
gap: 24px;
|
||||
align-items: center;
|
||||
padding: 30px 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
transition: background-color 0.18s ease, padding 0.18s ease;
|
||||
}
|
||||
|
||||
.document-number {
|
||||
color: var(--accent);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.7rem;
|
||||
letter-spacing: 0.1em;
|
||||
}
|
||||
|
||||
.document-copy {
|
||||
display: grid;
|
||||
gap: 7px;
|
||||
}
|
||||
|
||||
.document-copy strong {
|
||||
color: var(--fg);
|
||||
font-size: 1.2rem;
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.document-copy > span {
|
||||
color: var(--fg-dim);
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.document-arrow {
|
||||
color: var(--fg-dim);
|
||||
font-size: 1.25rem;
|
||||
transition: color 0.18s ease, transform 0.18s ease;
|
||||
}
|
||||
|
||||
@media (hover: hover) and (pointer: fine) {
|
||||
.document-card:hover {
|
||||
padding-left: 16px;
|
||||
padding-right: 16px;
|
||||
background: rgba(255, 255, 255, 0.025);
|
||||
}
|
||||
|
||||
.document-card:hover .document-arrow {
|
||||
color: var(--fg);
|
||||
transform: translate(2px, -2px);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 820px) {
|
||||
.legal-index {
|
||||
width: min(100% - 40px, 720px);
|
||||
padding-top: 56px;
|
||||
padding-bottom: 80px;
|
||||
}
|
||||
|
||||
.document-card {
|
||||
grid-template-columns: 30px minmax(0, 1fr) auto;
|
||||
gap: 14px;
|
||||
padding: 24px 4px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.legal-index {
|
||||
width: calc(100% - 32px);
|
||||
padding-top: 42px;
|
||||
}
|
||||
|
||||
.legal-index h1 {
|
||||
font-size: 4.4rem;
|
||||
}
|
||||
|
||||
.document-copy strong {
|
||||
font-size: 1.08rem;
|
||||
}
|
||||
|
||||
.document-copy > span {
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,445 @@
|
||||
---
|
||||
import LegalPage from "../components/LegalPage.astro";
|
||||
|
||||
const sections = [
|
||||
["introduction", "Introduction"],
|
||||
["information", "Personal information we collect"],
|
||||
["uses", "How we use your personal information"],
|
||||
["sharing", "How we share your personal information"],
|
||||
["choices", "Your choices regarding your personal information"],
|
||||
["security", "Security of your personal information"],
|
||||
["international", "International users"],
|
||||
["children", "Children"],
|
||||
["do-not-track", "Do Not Track"],
|
||||
["updates", "Updates to this Privacy Policy"],
|
||||
["contact", "Contact us"],
|
||||
] as const;
|
||||
---
|
||||
|
||||
<LegalPage
|
||||
title="Privacy Policy — T3 Code"
|
||||
description="How T3 Tools, Inc. handles information when you use T3 Code, app.t3.codes, and t3.codes."
|
||||
heading="T3 Code Privacy Policy"
|
||||
lede="This Privacy Policy describes how T3 Tools, Inc. collects, uses, and shares personal information when you use the T3 Code desktop, mobile, and hosted web applications, visit the t3.codes marketing site, or use the optional T3 Connect service."
|
||||
effectiveDate="2026-07-14"
|
||||
lastUpdated="2026-07-14"
|
||||
sections={sections}
|
||||
>
|
||||
<section id="introduction">
|
||||
<p class="section-number">01</p>
|
||||
<h2>Introduction</h2>
|
||||
<p>
|
||||
This Privacy Policy (the “Policy”) describes how T3 Tools, Inc. (the “Company,” “T3
|
||||
Tools,” “we,” or “us”) collects, uses, and shares personal information when you use the T3
|
||||
Code desktop and mobile applications, the hosted T3 Code web application located at
|
||||
{" "}<a href="https://app.t3.codes">https://app.t3.codes</a>, or the optional T3 Connect
|
||||
service (together, the “Services”), or visit the T3 Code marketing website located at
|
||||
{" "}<a href="https://t3.codes">https://t3.codes</a> (the “Site”). This Policy applies to
|
||||
personal information we collect through the Site and the Services, as well as personal
|
||||
information you provide to us directly.
|
||||
</p>
|
||||
<p>
|
||||
By using the Site or the Services, you acknowledge the practices described in this
|
||||
Policy. If you do not agree with this Policy, please do not use the Site or the Services.
|
||||
This Policy does not govern third-party coding agents, artificial-intelligence providers,
|
||||
identity providers, or environments that you choose to connect to T3 Code; those third
|
||||
parties process information under their own terms and privacy policies.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="information">
|
||||
<p class="section-number">02</p>
|
||||
<h2>Personal Information We Collect</h2>
|
||||
|
||||
<p>
|
||||
We collect personal information about you in different ways depending on how you use
|
||||
T3 Code and which optional features you enable.
|
||||
</p>
|
||||
|
||||
<h3>Personal Information From Users of T3 Code</h3>
|
||||
|
||||
<p>
|
||||
When you use T3 Code, we may collect the following categories of personal information:
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Account information.</strong> If you create or sign in to a T3 account, we
|
||||
receive general identifiers and profile information from our authentication provider
|
||||
and the identity provider you select. This may include your name, email address,
|
||||
profile image, user ID, sign-in method, and authentication credentials or tokens.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Environment and device information.</strong> If you enable T3 Connect, we
|
||||
process information needed to connect and secure your environments and devices,
|
||||
including identifiers, labels you assign, public keys, connection endpoints,
|
||||
credential hashes, connection status, app and operating-system versions, and
|
||||
notification preferences.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Agent activity and notifications.</strong> If you enable notifications or Live
|
||||
Activities, we process push tokens and limited activity information needed to provide
|
||||
those features, such as project and thread titles, model name, status, and activity
|
||||
headline.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Information you provide to us.</strong> We collect information that you choose
|
||||
to provide when you request support, send feedback, or otherwise communicate with us.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<h3>Personal Information From Users of Our Site Generally</h3>
|
||||
<p>
|
||||
When you visit the Site or use online portions of the Services, we and our service
|
||||
providers may automatically log online identifiers and internet-activity information,
|
||||
including your Internet Protocol (IP) address, device and operating-system type, browser
|
||||
or app type and version, pages viewed, access times, request timestamps, connection
|
||||
events, latency, error details, and diagnostic traces. The amount of information we
|
||||
collect depends on the Services you use and your device and browser settings.
|
||||
</p>
|
||||
<p>
|
||||
We use operational and diagnostic information to provide, secure, maintain, and
|
||||
troubleshoot the Services, not for targeted advertising.
|
||||
</p>
|
||||
|
||||
<h3>Information We Get From Others</h3>
|
||||
<p>
|
||||
We may receive personal information from service providers that help us operate the
|
||||
Services, such as authentication and identity providers, app stores, device-platform
|
||||
providers, and coding-agent providers you choose to use. We may combine this information
|
||||
with information we collect through the Site and the Services.
|
||||
</p>
|
||||
|
||||
<h3>Cookies and Local Storage</h3>
|
||||
<p>
|
||||
The Site and online portions of the Services may use cookies or similar technologies to
|
||||
operate essential features, maintain sessions, remember preferences, and understand
|
||||
whether the Services are functioning correctly. T3 Code also stores connection settings,
|
||||
credentials, preferences, drafts, and cached thread, file, branch, and server metadata on
|
||||
your device. Credentials and session tokens use platform-provided protected storage where
|
||||
supported. Information stored only on your device is not collected by T3 Tools unless it
|
||||
is transmitted as part of a feature you use.
|
||||
</p>
|
||||
|
||||
<h3>Device Permissions</h3>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Camera.</strong> Used when you choose to scan a pairing QR code. Camera frames
|
||||
are processed on your device.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Photos and files.</strong> Items you select are accessed only to preview them or
|
||||
attach them to a request you initiate.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Notifications.</strong> Used only if you enable agent-status notifications or
|
||||
Live Activities.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Local network.</strong> Used to discover or connect to T3 Code environments
|
||||
accessible from your machine over the network.
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section id="uses">
|
||||
<p class="section-number">03</p>
|
||||
<h2>How We Use Your Personal Information</h2>
|
||||
<p>
|
||||
Subject to this Policy and applicable terms governing third-party applications and
|
||||
services, we may use personal information for the following purposes:
|
||||
</p>
|
||||
<ul>
|
||||
<li>To establish and verify your identity and authenticate your account;</li>
|
||||
<li>To link and protect devices and environments and deliver optional notifications;</li>
|
||||
<li>To process and fulfill requests you make through the Services;</li>
|
||||
<li>To provide customer service and respond to support requests and feedback;</li>
|
||||
<li>To communicate with you about the Services and your relationship with us;</li>
|
||||
<li>To monitor reliability, prevent abuse, and investigate security incidents;</li>
|
||||
<li>To comply with applicable law and enforce the terms governing the Services; and</li>
|
||||
<li>
|
||||
To analyze and improve T3 Code using aggregated, de-identified, or other anonymous
|
||||
operational information.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<h3>Training of AI Models</h3>
|
||||
<p>
|
||||
We do not use your personal information, source code, prompts, or agent responses to
|
||||
train artificial-intelligence models.
|
||||
</p>
|
||||
|
||||
<h3>Compliance and Protection</h3>
|
||||
<p>We may use personal information to:</p>
|
||||
<ul>
|
||||
<li>Comply with applicable laws, lawful requests, and legal process;</li>
|
||||
<li>Protect the rights, privacy, safety, and property of T3 Tools, our users, and others;</li>
|
||||
<li>Audit our internal processes for legal, contractual, and policy compliance;</li>
|
||||
<li>Enforce the terms and conditions that govern the Site and the Services; and</li>
|
||||
<li>
|
||||
Prevent, identify, investigate, and deter fraudulent, harmful, unauthorized,
|
||||
unethical, or illegal activity, including cyberattacks and identity theft.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
We may also use personal information for other purposes consistent with this Policy or
|
||||
explained to you when we collect the information.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="sharing">
|
||||
<p class="section-number">04</p>
|
||||
<h2>How We Share Your Personal Information</h2>
|
||||
<p>
|
||||
We may disclose the categories of personal information described above to the following
|
||||
categories of third parties:
|
||||
</p>
|
||||
|
||||
<h3>Providers You Choose</h3>
|
||||
<p>
|
||||
At your direction, prompts, files, and related content are sent to coding agents and
|
||||
artificial-intelligence providers configured in your environment. Because you bring and
|
||||
configure your own coding-agent harness and provider, the applicable third parties vary.
|
||||
Those providers process information under their own terms and privacy policies.
|
||||
</p>
|
||||
|
||||
<h3>Third-Party Service Providers</h3>
|
||||
<p>
|
||||
We use third-party service providers to help provide the Services and operate our
|
||||
business. Depending on the features you use, these providers may include:
|
||||
</p>
|
||||
<ul class="provider-list">
|
||||
<li>
|
||||
<strong>Clerk</strong> <em>(Clerk, Inc.)</em>.<br />
|
||||
We use Clerk to provide account authentication.<br />
|
||||
You can view Clerk's privacy policy here:{" "}<a href="https://clerk.com/legal/privacy"
|
||||
>https://clerk.com/legal/privacy</a
|
||||
>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Cloudflare</strong> <em>(Cloudflare, Inc.)</em>.<br />
|
||||
We use Cloudflare for networking, T3 Connect infrastructure, and content delivery.<br />
|
||||
You can view Cloudflare's privacy policy here:{" "}<a
|
||||
href="https://www.cloudflare.com/policies/privacy/"
|
||||
>https://www.cloudflare.com/policies/privacy/</a
|
||||
>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>PlanetScale</strong> <em>(PlanetScale, Inc.)</em>.<br />
|
||||
We use PlanetScale to host the database that supports T3 Connect.<br />
|
||||
You can view PlanetScale's privacy policy here:{" "}<a
|
||||
href="https://planetscale.com/legal/privacy"
|
||||
>https://planetscale.com/legal/privacy</a
|
||||
>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Vercel</strong> <em>(Vercel Inc.)</em>.<br />
|
||||
We use Vercel to host and deploy the T3 Code Site.<br />
|
||||
You can view Vercel's privacy notice here:{" "}<a
|
||||
href="https://vercel.com/legal/privacy-notice"
|
||||
>https://vercel.com/legal/privacy-notice</a
|
||||
>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Axiom</strong> <em>(Axiom, Inc.)</em>.<br />
|
||||
We use Axiom for operational diagnostics that help us maintain and troubleshoot the
|
||||
Services.<br />
|
||||
You can view Axiom's privacy policy here:{" "}<a
|
||||
href="https://axiom.co/docs/legal/privacy">https://axiom.co/docs/legal/privacy</a
|
||||
>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Expo</strong> <em>(650 Industries, Inc.)</em>.<br />
|
||||
We use Expo for application updates and related mobile-app services.<br />
|
||||
You can view Expo's privacy policy here:{" "}<a href="https://expo.dev/privacy"
|
||||
>https://expo.dev/privacy</a
|
||||
>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Apple</strong> <em>(Apple Inc.)</em>.<br />
|
||||
We use Apple services for app distribution, optional authentication, and platform
|
||||
notifications.<br />
|
||||
You can view Apple's privacy policy here:{" "}<a
|
||||
href="https://www.apple.com/legal/privacy/">https://www.apple.com/legal/privacy/</a
|
||||
>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Google</strong> <em>(Google LLC)</em>.<br />
|
||||
We use Google services for app distribution and optional authentication.<br />
|
||||
You can view Google's privacy policy here:{" "}<a
|
||||
href="https://policies.google.com/privacy">https://policies.google.com/privacy</a
|
||||
>.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
These providers process information for us under their own contractual and privacy
|
||||
obligations.
|
||||
</p>
|
||||
|
||||
<h3>Affiliates and Professional Advisors</h3>
|
||||
<p>
|
||||
We may share personal information with our affiliates for purposes consistent with this
|
||||
Policy and with lawyers, accountants, bankers, and other professional advisors in the
|
||||
course of the services they provide to us.
|
||||
</p>
|
||||
|
||||
<h3>Corporate Restructuring</h3>
|
||||
<p>
|
||||
We may share some or all personal information in connection with or during negotiation of
|
||||
a merger, financing, acquisition, reorganization, bankruptcy, dissolution, sale of
|
||||
assets, or similar transaction. If another company acquires T3 Tools or its assets, that
|
||||
company may possess the personal information collected by us and assume the rights and
|
||||
obligations described in this Policy.
|
||||
</p>
|
||||
|
||||
<h3>Legal and Safety Disclosures</h3>
|
||||
<p>
|
||||
We may disclose personal information if we believe in good faith that disclosure is
|
||||
necessary to comply with law or legal process; protect or defend the rights, property, or
|
||||
safety of T3 Tools, users of the Site or the Services, or others; investigate or prevent
|
||||
fraud, abuse, or unlawful activity; or enforce this Policy and the terms governing the
|
||||
Services. We may also share personal information at your direction, with your consent, or
|
||||
as described to you when the information is collected.
|
||||
</p>
|
||||
|
||||
<h3>No Sale of Personal Information</h3>
|
||||
<p>
|
||||
We do not sell your personal information or share it for cross-context behavioral or
|
||||
targeted advertising.
|
||||
</p>
|
||||
|
||||
<h3>Third-Party Websites and Services</h3>
|
||||
<p>
|
||||
The Site and the Services may contain links to third-party websites or services. When you
|
||||
follow a third-party link or connect a third-party service, that third party may collect
|
||||
personal information from you. We do not control and are not responsible for the privacy
|
||||
practices or content of third parties.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="choices">
|
||||
<p class="section-number">05</p>
|
||||
<h2>Your Choices Regarding Your Personal Information</h2>
|
||||
|
||||
<h3>Account and Connection Choices</h3>
|
||||
<p>
|
||||
You may use local or direct connections without signing in to a T3 account. You can
|
||||
disconnect environments, sign out, disable optional notifications and Live Activities,
|
||||
and clear local caches from Settings. You can grant or revoke camera, photo, local-network,
|
||||
and notification permissions in your device settings.
|
||||
</p>
|
||||
|
||||
<h3>Cookies and Local Data</h3>
|
||||
<p>
|
||||
You can use your browser settings to stop accepting or to delete cookies, although some
|
||||
portions of the Site or the Services may not function correctly as a result. Information
|
||||
stored only on your device remains there until you clear it, remove the relevant
|
||||
connection, or uninstall the app. The mobile app provides cache controls under
|
||||
{" "}<strong>Settings → App → Client Storage</strong>.
|
||||
</p>
|
||||
|
||||
<h3>Retention and Deletion</h3>
|
||||
<p>
|
||||
We retain account, environment-link, device-registration, notification, and security
|
||||
information while your account or the relevant feature is active and for as long as
|
||||
reasonably necessary to provide the Services, protect them from abuse, comply with law,
|
||||
and resolve disputes. Operational diagnostic traces are configured to expire after 30
|
||||
days. Some records may remain longer in backups or where retention is required for
|
||||
security, fraud prevention, or legal compliance.
|
||||
</p>
|
||||
<p>
|
||||
To request deletion of your T3 account and associated T3 Connect data, email{" "}<a
|
||||
href="mailto:[email protected]">[email protected]</a
|
||||
>{" "}from the email address associated with your account. We may need to verify your
|
||||
identity. Deleting a T3 account does not delete information held by an environment or
|
||||
coding-agent provider you control; contact those providers or delete that information
|
||||
directly.
|
||||
</p>
|
||||
|
||||
<h3>Your Privacy Rights</h3>
|
||||
<p>
|
||||
Depending on where you live, you may have rights to request access to, correction of,
|
||||
deletion of, or a portable copy of your personal information, or to restrict or object
|
||||
to certain processing. You may also have the right to appeal our response or complain to
|
||||
a data-protection authority. We will honor applicable rights after verifying your
|
||||
request.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="security">
|
||||
<p class="section-number">06</p>
|
||||
<h2>Security of Your Personal Information</h2>
|
||||
<p>
|
||||
T3 Tools is committed to protecting the security of your personal information. We use
|
||||
administrative, technical, and organizational safeguards designed to protect personal
|
||||
information from unauthorized access, use, or disclosure. These safeguards include
|
||||
encrypted network transport, scoped and proof-bound access tokens for supported
|
||||
connection flows, protected credential storage, and redaction of authorization headers
|
||||
from relay diagnostics.
|
||||
</p>
|
||||
<p>
|
||||
No method of transmission over the Internet or method of electronic storage is completely
|
||||
secure. While we use reasonable efforts to protect personal information, we cannot
|
||||
guarantee its absolute security. You are responsible for securing the environments,
|
||||
coding-agent accounts, credentials, and networks that you connect to T3 Code.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="international">
|
||||
<p class="section-number">07</p>
|
||||
<h2>International Users</h2>
|
||||
<p>
|
||||
The Site and the Services are provided from the United States and are governed by United
|
||||
States law. If you use the Site or the Services from outside the United States, your
|
||||
personal information may be transferred to and processed in the United States and other
|
||||
countries where we or our service providers operate. Where required, we use lawful
|
||||
safeguards for international transfers of personal information.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="children">
|
||||
<p class="section-number">08</p>
|
||||
<h2>Children</h2>
|
||||
<p>
|
||||
The Site and the Services are not intended for children under 13 years of age, and you
|
||||
must be at least 13 years old to use them. We do not knowingly collect, use, or disclose
|
||||
personal information from children under 13. If you believe a child under 13 has provided
|
||||
us with personal information, please contact us so that we can take appropriate action.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="do-not-track">
|
||||
<p class="section-number">09</p>
|
||||
<h2>Do Not Track</h2>
|
||||
<p>
|
||||
We currently do not respond to browser “Do Not Track” signals. T3 Code does not use
|
||||
personal information for cross-context behavioral or targeted advertising.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="updates">
|
||||
<p class="section-number">10</p>
|
||||
<h2>Updates to This Privacy Policy</h2>
|
||||
<p>
|
||||
We reserve the right to update this Policy from time to time. If we make material changes,
|
||||
we will post the revised Policy at this URL, update the “Last Updated” and “Effective Date”
|
||||
above, and provide any additional notice required by law. Except as otherwise indicated,
|
||||
changes become effective when the revised Policy is posted.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="contact">
|
||||
<p class="section-number">11</p>
|
||||
<h2>Contact Us</h2>
|
||||
<p>
|
||||
If you have questions about this Policy or wish to make a privacy or deletion request,
|
||||
please contact us at:
|
||||
</p>
|
||||
<address>
|
||||
<strong>T3 Tools, Inc.</strong><br />
|
||||
2261 Market Street #5309<br />
|
||||
San Francisco, CA 94114<br />
|
||||
United States
|
||||
</address>
|
||||
<a class="contact-link" href="mailto:[email protected]">[email protected]</a>
|
||||
</section>
|
||||
</LegalPage>
|
||||
@@ -0,0 +1,187 @@
|
||||
---
|
||||
import LegalPage from "../components/LegalPage.astro";
|
||||
|
||||
const sections = [
|
||||
["introduction", "Introduction"],
|
||||
["reporting", "Reporting security issues"],
|
||||
["safe-harbor", "Responsible research and safe harbor"],
|
||||
["practices", "Our security practices"],
|
||||
["responsibilities", "Your responsibilities"],
|
||||
["updates", "Updates to this policy"],
|
||||
["contact", "Contact us"],
|
||||
] as const;
|
||||
---
|
||||
|
||||
<LegalPage
|
||||
title="Security Policy — T3 Code"
|
||||
description="How to report security issues in T3 Code and how T3 Tools approaches product security."
|
||||
heading="T3 Code Security Policy"
|
||||
lede="Security is a shared responsibility. This policy explains how to report a vulnerability, how we protect T3 Tools-operated services, and how you can secure the environments and providers you connect to T3 Code."
|
||||
effectiveDate="2026-07-15"
|
||||
lastUpdated="2026-07-15"
|
||||
sections={sections}
|
||||
>
|
||||
<section id="introduction">
|
||||
<p class="section-number">01</p>
|
||||
<h2>Introduction</h2>
|
||||
<p>
|
||||
This Security Policy describes the vulnerability-reporting process and security practices for
|
||||
the T3 Code desktop and mobile applications, the hosted application at{" "}<a
|
||||
href="https://app.t3.codes">https://app.t3.codes</a
|
||||
>, the optional T3 Connect service, and the T3 Code website at{" "}<a href="https://t3.codes"
|
||||
>https://t3.codes</a
|
||||
>.
|
||||
</p>
|
||||
<p>
|
||||
T3 Code connects software running on your devices and in environments you control with
|
||||
coding-agent harnesses and providers you choose. We secure the software and infrastructure
|
||||
operated by T3 Tools, but we do not control the security of your devices, environments,
|
||||
repositories, networks, credentials, or third-party providers. Please review the shared
|
||||
responsibilities below when assessing risk.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="reporting">
|
||||
<p class="section-number">02</p>
|
||||
<h2>Reporting Security Issues</h2>
|
||||
<p>
|
||||
If you believe you have found a security vulnerability affecting T3 Code or T3 Tools-operated
|
||||
infrastructure, email{" "}<a href="mailto:[email protected]">[email protected]</a>. Please do not
|
||||
disclose the issue publicly until we have had a reasonable opportunity to investigate and
|
||||
remediate it.
|
||||
</p>
|
||||
<p>Please include, when available:</p>
|
||||
<ul>
|
||||
<li>A description of the issue and its potential impact;</li>
|
||||
<li>The affected application, version, URL, endpoint, or component;</li>
|
||||
<li>Clear reproduction steps or a minimal proof of concept;</li>
|
||||
<li>Relevant logs, screenshots, or request and response details with secrets removed; and</li>
|
||||
<li>Your preferred contact information and whether you want public credit.</li>
|
||||
</ul>
|
||||
<p>
|
||||
We aim to acknowledge complete reports within one business day, keep reporters informed of
|
||||
material progress, and coordinate disclosure after a fix is available. Resolution time varies
|
||||
with severity, complexity, and dependencies on third parties.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="safe-harbor">
|
||||
<p class="section-number">03</p>
|
||||
<h2>Responsible Research and Safe Harbor</h2>
|
||||
<p>
|
||||
We support good-faith security research. If you make a genuine effort to comply with this
|
||||
policy, avoid harm, respect privacy, and report findings promptly, we will treat your research
|
||||
as authorized and will not initiate legal action against you for accidental, good-faith
|
||||
violations of this policy. If a third party initiates legal action concerning compliant
|
||||
research, we will make our authorization known where appropriate.
|
||||
</p>
|
||||
<p>To remain within this safe harbor, you must:</p>
|
||||
<ul>
|
||||
<li>Test only accounts, data, and systems you own or have explicit permission to test;</li>
|
||||
<li>Stop and report immediately if you encounter personal, confidential, or production data;</li>
|
||||
<li>Access only the minimum information needed to demonstrate the issue;</li>
|
||||
<li>Avoid disrupting availability, degrading performance, or damaging or deleting data;</li>
|
||||
<li>Not use social engineering, phishing, physical attacks, or denial-of-service testing;</li>
|
||||
<li>Not test third-party services or infrastructure outside T3 Tools’ control; and</li>
|
||||
<li>Give us reasonable time to address the issue before public disclosure.</li>
|
||||
</ul>
|
||||
<p>
|
||||
This safe harbor does not authorize violations of law or activity outside the scope of this
|
||||
policy. Vulnerability rewards are not guaranteed and, if offered, are determined by T3 Tools
|
||||
in its discretion.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="practices">
|
||||
<p class="section-number">04</p>
|
||||
<h2>Our Security Practices</h2>
|
||||
<p>
|
||||
We use administrative, technical, and organizational safeguards designed for the nature of T3
|
||||
Code and the information processed by T3 Tools-operated services. These practices include:
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Data minimization.</strong> T3 Code is designed so coding-session content can remain
|
||||
between your clients, your environment, and the harnesses and providers you configure. We
|
||||
process information through T3 Tools-operated infrastructure only when needed for a feature
|
||||
you enable.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Encrypted transport.</strong> T3 Tools-operated network services use encrypted
|
||||
transport. Supported connection flows use scoped credentials and security controls designed
|
||||
to reduce unauthorized reuse.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Credential protection.</strong> T3 Code uses platform-provided protected storage for
|
||||
credentials and session tokens where supported. We design operational logging to avoid
|
||||
collecting secrets that are not needed to operate or troubleshoot the Services.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Access controls.</strong> Access to production systems and operational data is limited
|
||||
according to job responsibilities and protected using authentication and authorization
|
||||
controls.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Maintenance and monitoring.</strong> We monitor T3 Tools-operated services for
|
||||
reliability and security events, review dependencies, and deploy updates and mitigations as
|
||||
appropriate.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Established providers.</strong> We use specialized providers for services such as
|
||||
authentication, hosting, and application distribution and evaluate the controls relevant to
|
||||
their role.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
No system is completely secure. These practices reduce risk but do not guarantee that the Site
|
||||
or Services will be free from vulnerabilities or unauthorized access.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="responsibilities">
|
||||
<p class="section-number">05</p>
|
||||
<h2>Your Responsibilities</h2>
|
||||
<p>
|
||||
Because you control much of the T3 Code execution path, you play an important role in securing
|
||||
it. You are responsible for:
|
||||
</p>
|
||||
<ul>
|
||||
<li>Keeping T3 Code, your operating systems, and connected tools up to date;</li>
|
||||
<li>Securing your devices, repositories, environments, networks, and backups;</li>
|
||||
<li>Protecting account, provider, repository, and environment credentials;</li>
|
||||
<li>Using multi-factor authentication where your identity and coding-agent providers support it;</li>
|
||||
<li>Granting providers and integrations only the permissions they need;</li>
|
||||
<li>Reviewing commands, source changes, and other agent output before applying or executing it;</li>
|
||||
<li>Removing lost or unused devices and revoking credentials you believe may be compromised; and</li>
|
||||
<li>Following the security policies of your selected harnesses, providers, and infrastructure.</li>
|
||||
</ul>
|
||||
<p>
|
||||
Do not send passwords, API keys, access tokens, or private keys in a vulnerability report.
|
||||
Revoke any secret that may have been exposed before sharing sanitized evidence with us.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="updates">
|
||||
<p class="section-number">06</p>
|
||||
<h2>Updates to This Policy</h2>
|
||||
<p>
|
||||
We may update this Security Policy as T3 Code, our infrastructure, and security practices
|
||||
evolve. We will post revisions at this URL and update the dates above. Material changes to the
|
||||
vulnerability-reporting process or safe-harbor terms will apply prospectively.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="contact">
|
||||
<p class="section-number">07</p>
|
||||
<h2>Contact Us</h2>
|
||||
<p>
|
||||
Report security issues or ask security-related questions at{" "}<a
|
||||
href="mailto:[email protected]">[email protected]</a
|
||||
>.
|
||||
</p>
|
||||
<p>
|
||||
For general legal questions, contact{" "}<a href="mailto:[email protected]">[email protected]</a>.
|
||||
For privacy requests, contact{" "}<a href="mailto:[email protected]">[email protected]</a>.
|
||||
</p>
|
||||
</section>
|
||||
</LegalPage>
|
||||
@@ -0,0 +1,396 @@
|
||||
---
|
||||
import LegalPage from "../components/LegalPage.astro";
|
||||
|
||||
const sections = [
|
||||
["introduction", "Introduction"],
|
||||
["accounts", "Accounts"],
|
||||
["content", "Your content and providers"],
|
||||
["rights", "T3 Code and proprietary rights"],
|
||||
["acceptable-use", "Acceptable use"],
|
||||
["availability", "Availability and changes"],
|
||||
["fees", "Fees"],
|
||||
["privacy", "Privacy"],
|
||||
["termination", "Suspension and termination"],
|
||||
["beta", "Beta services"],
|
||||
["disclaimers", "Disclaimers"],
|
||||
["liability", "Limitation of liability"],
|
||||
["indemnification", "Indemnification"],
|
||||
["copyright", "Copyright complaints"],
|
||||
["third-parties", "Third-party services"],
|
||||
["feedback", "Feedback"],
|
||||
["disputes", "Dispute resolution"],
|
||||
["miscellaneous", "Miscellaneous"],
|
||||
["changes", "Changes to these Terms"],
|
||||
["contact", "Contact us"],
|
||||
] as const;
|
||||
---
|
||||
|
||||
<LegalPage
|
||||
title="Terms of Service — T3 Code"
|
||||
description="The terms that govern your use of T3 Code, app.t3.codes, T3 Connect, and t3.codes."
|
||||
heading="T3 Code Terms of Service"
|
||||
lede="These Terms govern your use of T3 Code, including its desktop, mobile, and hosted applications, the optional T3 Connect service, and the t3.codes website."
|
||||
effectiveDate="2026-07-15"
|
||||
lastUpdated="2026-07-15"
|
||||
sections={sections}
|
||||
>
|
||||
<section id="introduction">
|
||||
<p class="section-number">01</p>
|
||||
<h2>Introduction</h2>
|
||||
<p>
|
||||
These Terms of Service (the “Terms”) are a binding agreement between you and T3 Tools, Inc.
|
||||
(“T3 Tools,” “we,” “us,” or “our”). They govern your access to and use of the T3 Code desktop
|
||||
and mobile applications, the hosted T3 Code application at{" "}<a href="https://app.t3.codes"
|
||||
>https://app.t3.codes</a
|
||||
>, and the optional T3 Connect service (together, the “Services”), as well as the T3 Code
|
||||
marketing website at{" "}<a href="https://t3.codes">https://t3.codes</a> (the “Site”).
|
||||
</p>
|
||||
<p>
|
||||
By accessing or using the Site or Services, you agree to these Terms. If you use the Services
|
||||
for an organization, you represent that you have authority to bind that organization, and
|
||||
“you” includes the organization. If you do not agree to these Terms, do not use the Site or
|
||||
Services.
|
||||
</p>
|
||||
<p>
|
||||
You must be at least 13 years old to use the Site or Services. If the law where you live
|
||||
requires a greater age to enter into these Terms, you must meet that requirement or have a
|
||||
parent or legal guardian agree on your behalf.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="accounts">
|
||||
<p class="section-number">02</p>
|
||||
<h2>Accounts</h2>
|
||||
<p>
|
||||
You can use some T3 Code features without creating a T3 account. An account may be required
|
||||
for account-backed features, including T3 Connect. You agree to provide accurate account
|
||||
information, keep your credentials secure, and promptly notify us if you suspect unauthorized
|
||||
access. You are responsible for activity performed through your account and connected devices,
|
||||
except to the extent caused by our failure to use reasonable security measures.
|
||||
</p>
|
||||
<p>
|
||||
You may not share credentials in a way that compromises the Services, impersonate another
|
||||
person, or create accounts through unauthorized automated means. We may require reasonable
|
||||
verification before restoring access or acting on an account request.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="content">
|
||||
<p class="section-number">03</p>
|
||||
<h2>Your Content and Providers</h2>
|
||||
<p>
|
||||
T3 Code can help you send prompts, source files, images, attachments, review comments, and
|
||||
instructions to coding-agent harnesses and providers you choose, and display their responses,
|
||||
command output, file changes, source code, and diffs (collectively, “User Content”). You retain
|
||||
all rights you have in your User Content.
|
||||
</p>
|
||||
<p>
|
||||
You bring and configure your own coding-agent harness and provider. Your User Content is
|
||||
ordinarily processed in the environment you control and by the providers you select, not by
|
||||
T3 Tools. When you enable a T3 Tools-operated feature that must transmit or process User
|
||||
Content, you grant us a limited, non-exclusive license to host, transmit, reproduce, and
|
||||
process that content only as reasonably necessary to provide, secure, and troubleshoot that
|
||||
feature. This license ends when the content is no longer needed for those purposes, subject to
|
||||
reasonable backup, security, and legal-retention requirements.
|
||||
</p>
|
||||
<p>
|
||||
You represent that you have the rights and permissions needed to use and submit User Content
|
||||
and to direct its processing by your selected harnesses and providers. You are responsible for
|
||||
reviewing those providers’ terms, privacy practices, data controls, and output before using
|
||||
them with confidential, proprietary, regulated, or personal information.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="rights">
|
||||
<p class="section-number">04</p>
|
||||
<h2>T3 Code and Proprietary Rights</h2>
|
||||
<p>
|
||||
T3 Tools and its licensors own the Site, the Services, and their branding, designs, hosted
|
||||
infrastructure, documentation, and other materials, excluding User Content and third-party
|
||||
materials. These Terms do not transfer ownership of either party’s intellectual property.
|
||||
</p>
|
||||
<p>
|
||||
Portions of T3 Code are available as open-source software. Your use, copying, modification, and
|
||||
distribution of that source code are governed by the license included with the applicable
|
||||
repository or component. These Terms govern your use of the hosted Services and do not limit
|
||||
rights granted to you by an applicable open-source license.
|
||||
</p>
|
||||
<p>
|
||||
Subject to these Terms, we grant you a limited, non-exclusive, non-transferable, revocable right
|
||||
to access and use the Services for lawful personal or internal business purposes. You may not
|
||||
use our trademarks, service marks, or trade dress without written permission.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="acceptable-use">
|
||||
<p class="section-number">05</p>
|
||||
<h2>Acceptable Use</h2>
|
||||
<p>You may not use the Site or Services to:</p>
|
||||
<ul>
|
||||
<li>Violate applicable law or another person’s rights;</li>
|
||||
<li>Upload, transmit, or generate content you do not have the right to use;</li>
|
||||
<li>Distribute malware, exploit code, or harmful content except in authorized security work;</li>
|
||||
<li>Probe, attack, disrupt, or gain unauthorized access to the Services or another system;</li>
|
||||
<li>Bypass rate limits, access controls, security measures, or usage restrictions;</li>
|
||||
<li>Interfere with other users or place an unreasonable load on shared infrastructure;</li>
|
||||
<li>Use the Services to facilitate fraud, harassment, abuse, or deceptive conduct; or</li>
|
||||
<li>Misrepresent that output or activity from a third-party agent was produced or endorsed by us.</li>
|
||||
</ul>
|
||||
<p>
|
||||
Authorized security research must follow our{" "}<a href="/security-policy">Security Policy</a>.
|
||||
We may investigate suspected violations and take proportionate action to protect users and the
|
||||
Services.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="availability">
|
||||
<p class="section-number">06</p>
|
||||
<h2>Availability and Changes</h2>
|
||||
<p>
|
||||
We may add, change, suspend, or discontinue features, integrations, or supported platforms. We
|
||||
aim to provide reasonable notice when a change materially reduces an account-backed feature,
|
||||
but urgent security, legal, or reliability changes may take effect immediately. The Services
|
||||
may be unavailable because of maintenance, provider outages, network conditions, or events
|
||||
outside our control.
|
||||
</p>
|
||||
<p>
|
||||
T3 Code depends on software, environments, networks, and coding-agent providers that you
|
||||
configure or that third parties operate. We do not control their availability, compatibility,
|
||||
pricing, or behavior.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="fees">
|
||||
<p class="section-number">07</p>
|
||||
<h2>Fees</h2>
|
||||
<p>
|
||||
T3 Code is currently offered without a T3 Tools subscription fee unless we clearly state
|
||||
otherwise for a feature. You remain responsible for charges from your coding-agent providers,
|
||||
cloud infrastructure, network operators, app stores, and other third parties. If we introduce
|
||||
a paid feature, we will present its price and applicable payment terms before you purchase it.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="privacy">
|
||||
<p class="section-number">08</p>
|
||||
<h2>Privacy</h2>
|
||||
<p>
|
||||
Our{" "}<a href="/privacy-policy">Privacy Policy</a> explains how T3 Tools collects, uses, and
|
||||
shares personal information when you use the Site and Services. Third-party environments,
|
||||
harnesses, identity providers, and coding-agent providers process information under their own
|
||||
terms and privacy policies.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="termination">
|
||||
<p class="section-number">09</p>
|
||||
<h2>Suspension and Termination</h2>
|
||||
<p>
|
||||
You may stop using the Services at any time. You may disconnect environments and devices from
|
||||
within T3 Code and may request deletion of an account as described in our Privacy Policy.
|
||||
</p>
|
||||
<p>
|
||||
We may suspend or terminate access to account-backed or hosted features if we reasonably
|
||||
believe you materially violated these Terms, created a security or legal risk, failed to pay an
|
||||
applicable fee, or used the Services in a way that could harm other users or shared
|
||||
infrastructure. When practicable, we will give notice and an opportunity to cure. We may act
|
||||
immediately where needed to prevent harm or comply with law.
|
||||
</p>
|
||||
<p>
|
||||
Provisions that by their nature should survive termination—including ownership, disclaimers,
|
||||
limitations of liability, indemnification, and dispute terms—will survive.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="beta">
|
||||
<p class="section-number">10</p>
|
||||
<h2>Beta Services</h2>
|
||||
<p>
|
||||
T3 Code is an early-stage product, and some or all features may be identified as alpha, beta,
|
||||
preview, experimental, or pre-release (“Beta Services”). Beta Services may be incomplete,
|
||||
change without notice, contain errors, or lose data. Do not rely on Beta Services as the sole
|
||||
copy of important work, and review proposed commands and file changes before applying them.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="disclaimers">
|
||||
<p class="section-number">11</p>
|
||||
<h2>Disclaimers</h2>
|
||||
<p class="legal-notice">
|
||||
TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE SITE AND SERVICES ARE PROVIDED “AS IS” AND “AS
|
||||
AVAILABLE,” WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
|
||||
</p>
|
||||
<p>
|
||||
Coding agents and artificial-intelligence systems can produce incorrect, insecure, incomplete,
|
||||
or harmful output. You are responsible for reviewing output, commands, patches, and other
|
||||
actions before relying on or executing them. We do not warrant that the Services or third-party
|
||||
output will be uninterrupted, secure, accurate, error-free, or suitable for your purpose.
|
||||
</p>
|
||||
<p>
|
||||
Some jurisdictions do not allow certain warranty exclusions, so some of the foregoing may not
|
||||
apply to you.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="liability">
|
||||
<p class="section-number">12</p>
|
||||
<h2>Limitation of Liability</h2>
|
||||
<p class="legal-notice">
|
||||
TO THE MAXIMUM EXTENT PERMITTED BY LAW, T3 TOOLS AND ITS AFFILIATES, OFFICERS, EMPLOYEES,
|
||||
AGENTS, AND LICENSORS WILL NOT BE LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL,
|
||||
EXEMPLARY, OR PUNITIVE DAMAGES, OR FOR LOST PROFITS, REVENUE, DATA, GOODWILL, OR BUSINESS
|
||||
OPPORTUNITIES, ARISING FROM OR RELATED TO THE SITE, SERVICES, OR THESE TERMS.
|
||||
</p>
|
||||
<p>
|
||||
To the maximum extent permitted by law, our aggregate liability for all claims arising from or
|
||||
relating to the Site, Services, or these Terms will not exceed the greater of $100 or the amount
|
||||
you paid directly to T3 Tools for the Services during the 12 months before the event giving rise
|
||||
to the claim. These limitations apply regardless of the legal theory and even if a remedy fails
|
||||
of its essential purpose. They do not limit liability that cannot lawfully be limited.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="indemnification">
|
||||
<p class="section-number">13</p>
|
||||
<h2>Indemnification</h2>
|
||||
<p>
|
||||
To the extent permitted by law, you will defend, indemnify, and hold harmless T3 Tools and its
|
||||
affiliates, officers, employees, and agents from third-party claims, damages, losses, and
|
||||
reasonable legal fees arising from your User Content, your use of the Site or Services in
|
||||
violation of these Terms or law, or your infringement of another person’s rights. We will
|
||||
promptly notify you of a covered claim and reasonably cooperate in its defense. You may not
|
||||
settle a claim in a way that admits fault by or imposes obligations on us without our written
|
||||
consent.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="copyright">
|
||||
<p class="section-number">14</p>
|
||||
<h2>Copyright Complaints</h2>
|
||||
<p>
|
||||
If you believe material available through a T3 Tools-operated part of the Site or Services
|
||||
infringes your copyright, send a notice to{" "}<a href="mailto:[email protected]">[email protected]</a
|
||||
>{" "}identifying the copyrighted work, the allegedly infringing material and its location, your
|
||||
contact information, a statement of good-faith belief, a statement under penalty of perjury
|
||||
that the notice is accurate and you are authorized to act, and your physical or electronic
|
||||
signature.
|
||||
</p>
|
||||
<p>
|
||||
T3 Tools does not control content stored only in a user’s environment or held by a user-selected
|
||||
provider. Requests concerning that material should be directed to the operator that hosts it.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="third-parties">
|
||||
<p class="section-number">15</p>
|
||||
<h2>Third-Party Services</h2>
|
||||
<p>
|
||||
The Services may connect to or display content from third-party coding agents, model providers,
|
||||
identity providers, repositories, app stores, websites, and infrastructure. Your use of those
|
||||
services is governed by their terms. We do not endorse or control third-party services and are
|
||||
not responsible for their content, security, availability, output, or data practices.
|
||||
</p>
|
||||
<p>
|
||||
Third-party and open-source software included with T3 Code is governed by its applicable
|
||||
license notices. Where those licenses conflict with these Terms for that software, the
|
||||
applicable open-source license controls.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="feedback">
|
||||
<p class="section-number">16</p>
|
||||
<h2>Feedback</h2>
|
||||
<p>
|
||||
If you send us ideas, suggestions, or other feedback about T3 Code, you grant T3 Tools a
|
||||
perpetual, irrevocable, worldwide, royalty-free right to use and commercialize that feedback
|
||||
without restriction or compensation. This does not transfer ownership of your User Content.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="disputes">
|
||||
<p class="section-number">17</p>
|
||||
<h2>Dispute Resolution</h2>
|
||||
<p class="legal-notice">
|
||||
PLEASE READ THIS SECTION CAREFULLY. IT REQUIRES MOST DISPUTES TO BE RESOLVED BY INDIVIDUAL
|
||||
BINDING ARBITRATION AND WAIVES JURY TRIALS AND CLASS OR REPRESENTATIVE ACTIONS.
|
||||
</p>
|
||||
<h3>Informal Resolution</h3>
|
||||
<p>
|
||||
Before starting arbitration or a court proceeding, the party raising a dispute must send a
|
||||
written notice describing the dispute and requested relief. Notices to us must be sent to{" "}<a
|
||||
href="mailto:[email protected]">[email protected]</a
|
||||
>. The parties will try in good faith to resolve the dispute for at least 30 days.
|
||||
</p>
|
||||
<h3>Binding Arbitration</h3>
|
||||
<p>
|
||||
Except for disputes eligible for small-claims court and requests for injunctive relief to
|
||||
protect intellectual property or prevent unauthorized access, unresolved disputes will be
|
||||
resolved by binding individual arbitration administered by JAMS under its applicable consumer
|
||||
or comprehensive rules. The Federal Arbitration Act governs this agreement. Arbitration may
|
||||
take place remotely unless the arbitrator determines that an in-person hearing is necessary.
|
||||
</p>
|
||||
<h3>No Class Actions</h3>
|
||||
<p>
|
||||
Disputes must be brought only on an individual basis. Neither party may participate in a class,
|
||||
collective, consolidated, or representative action or arbitration to the extent permitted by
|
||||
law.
|
||||
</p>
|
||||
<h3>Opt Out</h3>
|
||||
<p>
|
||||
You may opt out of this arbitration agreement by emailing{" "}<a href="mailto:[email protected]"
|
||||
>[email protected]</a
|
||||
> within 30 days after you first accept these Terms. Include your name, the email associated
|
||||
with your account if any, and a clear statement that you opt out of arbitration.
|
||||
</p>
|
||||
<p>
|
||||
If the arbitration agreement does not apply, exclusive jurisdiction and venue will lie in the
|
||||
state and federal courts located in San Francisco County, California, and each party consents
|
||||
to those courts.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="miscellaneous">
|
||||
<p class="section-number">18</p>
|
||||
<h2>Miscellaneous</h2>
|
||||
<p>
|
||||
California law governs these Terms without regard to conflict-of-law principles, except that
|
||||
the Federal Arbitration Act governs the arbitration provisions. These Terms and documents
|
||||
incorporated by reference are the entire agreement between you and us regarding the Site and
|
||||
Services. If a provision is unenforceable, it will be modified to the minimum extent necessary
|
||||
or severed, and the remaining provisions will continue in effect.
|
||||
</p>
|
||||
<p>
|
||||
Our failure to enforce a provision is not a waiver. You may not assign these Terms without our
|
||||
written consent. We may assign them in connection with a merger, acquisition, reorganization,
|
||||
or sale of assets. We are not liable for delays or failures caused by events beyond our
|
||||
reasonable control. Headings are for convenience only, and “including” means “including without
|
||||
limitation.”
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="changes">
|
||||
<p class="section-number">19</p>
|
||||
<h2>Changes to These Terms</h2>
|
||||
<p>
|
||||
We may update these Terms from time to time. We will post updated Terms at this URL and update
|
||||
the dates above. If a change materially affects your rights, we will provide additional notice
|
||||
when reasonably practicable or as required by law. Changes apply prospectively from their
|
||||
effective date. Your continued use of the Site or Services after that date means you accept the
|
||||
updated Terms.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="contact">
|
||||
<p class="section-number">20</p>
|
||||
<h2>Contact Us</h2>
|
||||
<p>If you have questions about these Terms, contact us at:</p>
|
||||
<address>
|
||||
<strong>T3 Tools, Inc.</strong><br />
|
||||
2261 Market Street #5309<br />
|
||||
San Francisco, CA 94114<br />
|
||||
United States
|
||||
</address>
|
||||
<a class="contact-link" href="mailto:[email protected]">[email protected]</a>
|
||||
</section>
|
||||
</LegalPage>
|
||||
@@ -35,8 +35,8 @@ vp run ios:dev
|
||||
```
|
||||
|
||||
If your Xcode account only has a Personal Team, use a bundle identifier you control and opt into the
|
||||
reduced-capability local build. Personal Team builds omit the widget extension, push entitlement, and
|
||||
native Sign in with Apple entitlement; builds without this opt-in are unchanged.
|
||||
reduced-capability local build. Personal Team builds omit the widget and share extensions, push
|
||||
entitlement, and native Sign in with Apple entitlement; builds without this opt-in are unchanged.
|
||||
|
||||
```bash
|
||||
T3CODE_IOS_PERSONAL_TEAM=1 \
|
||||
|
||||
@@ -23,46 +23,54 @@ if (
|
||||
);
|
||||
}
|
||||
|
||||
const VARIANT_CONFIG: Record<
|
||||
AppVariant,
|
||||
{
|
||||
readonly appName: string;
|
||||
readonly scheme: string;
|
||||
readonly iosIcon: string;
|
||||
readonly splashIcon: string;
|
||||
readonly iosBundleIdentifier: string;
|
||||
readonly androidPackage: string;
|
||||
readonly relyingParty?: string;
|
||||
}
|
||||
> = {
|
||||
const DEVELOPMENT_ASSETS = {
|
||||
appIcon: "./assets/splash-icon-dev.png",
|
||||
iosIcon: "./assets/icon-composer-dev.icon",
|
||||
splashIcon: "./assets/splash-icon-dev.png",
|
||||
androidAdaptiveForeground: "./assets/android-icon-dev-foreground.png",
|
||||
androidAdaptiveBackgroundColor: "#00639B",
|
||||
androidMonochromeIcon: "./assets/android-icon-mark.png",
|
||||
androidNotificationIcon: "./assets/android-notification-icon.png",
|
||||
androidNotificationColor: "#00639B",
|
||||
} as const;
|
||||
|
||||
const RELEASE_ASSETS = {
|
||||
appIcon: "./assets/splash-icon-prod.png",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
androidAdaptiveForeground: "./assets/android-icon-mark.png",
|
||||
androidAdaptiveBackgroundColor: "#000000",
|
||||
androidMonochromeIcon: "./assets/android-icon-mark.png",
|
||||
androidNotificationIcon: "./assets/android-notification-icon.png",
|
||||
androidNotificationColor: "#FFFFFF",
|
||||
} as const;
|
||||
|
||||
const VARIANT_CONFIG = {
|
||||
development: {
|
||||
appName: "T3 Code Dev",
|
||||
scheme: "t3code-dev",
|
||||
iosIcon: "./assets/icon-composer-dev.icon",
|
||||
splashIcon: "./assets/splash-icon-dev.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code.dev",
|
||||
androidPackage: "com.t3tools.t3code.dev",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
assets: DEVELOPMENT_ASSETS,
|
||||
},
|
||||
preview: {
|
||||
appName: "T3 Code Preview",
|
||||
scheme: "t3code-preview",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code.preview",
|
||||
androidPackage: "com.t3tools.t3code.preview",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
assets: RELEASE_ASSETS,
|
||||
},
|
||||
production: {
|
||||
appName: "T3 Code",
|
||||
scheme: "t3code",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
iosBundleIdentifier: "com.t3tools.t3code",
|
||||
androidPackage: "com.t3tools.t3code",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
assets: RELEASE_ASSETS,
|
||||
},
|
||||
};
|
||||
} as const;
|
||||
|
||||
function resolveAppVariant(value: string | undefined): AppVariant {
|
||||
switch (value) {
|
||||
@@ -76,6 +84,9 @@ function resolveAppVariant(value: string | undefined): AppVariant {
|
||||
}
|
||||
|
||||
const variant = VARIANT_CONFIG[APP_VARIANT];
|
||||
const iosBundleIdentifier = isIosPersonalTeamBuild
|
||||
? personalTeamBundleIdentifier!
|
||||
: variant.iosBundleIdentifier;
|
||||
|
||||
const dmSansFonts = {
|
||||
regular: "@expo-google-fonts/dm-sans/400Regular/DMSans_400Regular.ttf",
|
||||
@@ -86,8 +97,8 @@ const dmSansFonts = {
|
||||
const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
|
||||
"expo-widgets",
|
||||
{
|
||||
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
|
||||
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
|
||||
bundleIdentifier: `${iosBundleIdentifier}.widgets`,
|
||||
groupIdentifier: `group.${iosBundleIdentifier}`,
|
||||
enablePushNotifications: true,
|
||||
// Agent activity can update many times an hour; without the
|
||||
// frequent-updates entitlement iOS throttles the update budget sooner.
|
||||
@@ -103,6 +114,30 @@ const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
|
||||
},
|
||||
];
|
||||
|
||||
const sharingPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
|
||||
"expo-sharing",
|
||||
{
|
||||
ios: {
|
||||
// Personal Teams cannot sign App Groups or extension targets. Keep the
|
||||
// reduced-capability local build usable while release builds expose the
|
||||
// real system share target.
|
||||
enabled: !isIosPersonalTeamBuild,
|
||||
extensionBundleIdentifier: `${iosBundleIdentifier}.sharing`,
|
||||
appGroupId: `group.${iosBundleIdentifier}`,
|
||||
activationRule: {
|
||||
supportsText: true,
|
||||
supportsWebUrlWithMaxCount: 1,
|
||||
supportsImageWithMaxCount: 8,
|
||||
},
|
||||
},
|
||||
android: {
|
||||
enabled: true,
|
||||
singleShareMimeTypes: ["text/plain", "image/*"],
|
||||
multipleShareMimeTypes: ["image/*"],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// These aliases match the fonts' PostScript names on iOS. Register the same
|
||||
// names on Android so React Native and the native composer use one set of
|
||||
// family names without waiting for runtime font loading.
|
||||
@@ -121,7 +156,7 @@ const config: ExpoConfig = {
|
||||
policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint",
|
||||
},
|
||||
orientation: "portrait",
|
||||
icon: "./assets/icon.png",
|
||||
icon: variant.assets.appIcon,
|
||||
userInterfaceStyle: "automatic",
|
||||
updates: {
|
||||
enabled: true,
|
||||
@@ -130,9 +165,9 @@ const config: ExpoConfig = {
|
||||
fallbackToCacheTimeout: 0,
|
||||
},
|
||||
ios: {
|
||||
icon: variant.iosIcon,
|
||||
icon: variant.assets.iosIcon,
|
||||
supportsTablet: true,
|
||||
bundleIdentifier: variant.iosBundleIdentifier,
|
||||
bundleIdentifier: iosBundleIdentifier,
|
||||
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
|
||||
// does not fall back to a personal team (which cannot sign app groups,
|
||||
// Sign in with Apple, or push notification entitlements).
|
||||
@@ -151,13 +186,12 @@ const config: ExpoConfig = {
|
||||
},
|
||||
},
|
||||
android: {
|
||||
icon: "./assets/icon.png",
|
||||
icon: variant.assets.appIcon,
|
||||
package: variant.androidPackage,
|
||||
adaptiveIcon: {
|
||||
backgroundColor: "#E6F4FE",
|
||||
foregroundImage: "./assets/android-icon-foreground.png",
|
||||
backgroundImage: "./assets/android-icon-background.png",
|
||||
monochromeImage: "./assets/android-icon-monochrome.png",
|
||||
backgroundColor: variant.assets.androidAdaptiveBackgroundColor,
|
||||
foregroundImage: variant.assets.androidAdaptiveForeground,
|
||||
monochromeImage: variant.assets.androidMonochromeIcon,
|
||||
},
|
||||
// Opts into OnBackInvokedCallback-based back dispatch (Android 13+).
|
||||
// JS back handling survives it via react-native's Android 16 shim plus
|
||||
@@ -165,7 +199,7 @@ const config: ExpoConfig = {
|
||||
predictiveBackGestureEnabled: true,
|
||||
},
|
||||
web: {
|
||||
favicon: "./assets/favicon.png",
|
||||
favicon: variant.assets.appIcon,
|
||||
},
|
||||
plugins: [
|
||||
"expo-asset",
|
||||
@@ -195,6 +229,17 @@ const config: ExpoConfig = {
|
||||
],
|
||||
"expo-secure-store",
|
||||
"expo-sqlite",
|
||||
...(isIosPersonalTeamBuild
|
||||
? [sharingPlugin]
|
||||
: ["./plugins/withShareExtensionDisplayName.cjs", sharingPlugin]),
|
||||
[
|
||||
"expo-notifications",
|
||||
{
|
||||
icon: variant.assets.androidNotificationIcon,
|
||||
color: variant.assets.androidNotificationColor,
|
||||
mode: APP_VARIANT === "development" ? "development" : "production",
|
||||
},
|
||||
],
|
||||
// appleSignIn must be gated here: withoutIosPersonalTeamCapabilities.cjs runs before
|
||||
// plugins earlier in this array, so it cannot strip the entitlement Clerk would add.
|
||||
["@clerk/expo", { theme: "./clerk-theme.json", appleSignIn: !isIosPersonalTeamBuild }],
|
||||
@@ -206,8 +251,8 @@ const config: ExpoConfig = {
|
||||
// the shortcut items set in src/features/shortcuts.
|
||||
androidIcons: {
|
||||
shortcut_icon: {
|
||||
foregroundImage: "./assets/android-icon-foreground.png",
|
||||
backgroundColor: "#E6F4FE",
|
||||
foregroundImage: variant.assets.androidAdaptiveForeground,
|
||||
backgroundColor: variant.assets.androidAdaptiveBackgroundColor,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -217,17 +262,18 @@ const config: ExpoConfig = {
|
||||
{
|
||||
cameraPermission: "Allow T3 Code to access your camera so you can scan pairing QR codes.",
|
||||
barcodeScannerEnabled: true,
|
||||
recordAudioAndroid: false,
|
||||
},
|
||||
],
|
||||
[
|
||||
"expo-splash-screen",
|
||||
{
|
||||
image: variant.splashIcon,
|
||||
image: variant.assets.splashIcon,
|
||||
resizeMode: "contain",
|
||||
backgroundColor: "#ffffff",
|
||||
imageWidth: 220,
|
||||
dark: {
|
||||
image: variant.splashIcon,
|
||||
image: variant.assets.splashIcon,
|
||||
backgroundColor: "#0a0a0a",
|
||||
},
|
||||
},
|
||||
|
||||
|
Before Width: | Height: | Size: 323 KiB After Width: | Height: | Size: 323 KiB |
|
Before Width: | Height: | Size: 323 KiB |
|
After Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 323 KiB |
|
After Width: | Height: | Size: 733 B |
|
Before Width: | Height: | Size: 74 KiB |
|
Before Width: | Height: | Size: 2.0 MiB |
@@ -1,5 +1,6 @@
|
||||
import { registerRootComponent } from "expo";
|
||||
import "react-native-gesture-handler";
|
||||
import { LogBox } from "react-native";
|
||||
import { featureFlags } from "react-native-screens";
|
||||
|
||||
import App from "./src/App";
|
||||
@@ -8,4 +9,8 @@ import App from "./src/App";
|
||||
// native stack is rendered inside a non-fitToContents formSheet.
|
||||
featureFlags.experiment.synchronousScreenUpdatesEnabled = true;
|
||||
|
||||
if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
|
||||
LogBox.ignoreAllLogs();
|
||||
}
|
||||
|
||||
registerRootComponent(App);
|
||||
@@ -7,6 +7,32 @@ class T3NativeControlsModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("T3NativeControls")
|
||||
|
||||
Function("getShowcasePairingUrl") {
|
||||
appContext.currentActivity?.intent?.getStringExtra("showcasePairingUrl")
|
||||
}
|
||||
|
||||
Function("getShowcaseScene") {
|
||||
val storedScene = appContext.reactContext
|
||||
?.filesDir
|
||||
?.resolve("t3-showcase-scene")
|
||||
?.takeIf { it.isFile }
|
||||
?.readText()
|
||||
?.trim()
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
storedScene ?: appContext.currentActivity?.intent?.getStringExtra("showcaseScene")
|
||||
}
|
||||
|
||||
Function("prepareShowcaseCapture") {
|
||||
// Android app data is cleared by the host runner before launch.
|
||||
}
|
||||
|
||||
Function("markShowcaseReady") { scene: String ->
|
||||
appContext.reactContext
|
||||
?.filesDir
|
||||
?.resolve("t3-showcase-ready")
|
||||
?.writeText(scene)
|
||||
}
|
||||
|
||||
View(T3HeaderButtonView::class) {
|
||||
Prop("label") { view: T3HeaderButtonView, label: String ->
|
||||
view.setLabel(label)
|
||||
|
||||
@@ -1,9 +1,48 @@
|
||||
import ExpoModulesCore
|
||||
import Security
|
||||
|
||||
public final class T3NativeControlsModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("T3NativeControls")
|
||||
|
||||
Function("getShowcasePairingUrl") {
|
||||
let arguments = ProcessInfo.processInfo.arguments
|
||||
guard
|
||||
let flagIndex = arguments.firstIndex(of: "--showcasePairingUrl"),
|
||||
arguments.indices.contains(flagIndex + 1)
|
||||
else {
|
||||
return nil as String?
|
||||
}
|
||||
return arguments[flagIndex + 1]
|
||||
}
|
||||
|
||||
Function("getShowcaseScene") { () -> String? in
|
||||
let scenePath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseScene"
|
||||
if let storedScene = try? String(contentsOfFile: scenePath, encoding: .utf8)
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines), !storedScene.isEmpty {
|
||||
return storedScene
|
||||
}
|
||||
let arguments = ProcessInfo.processInfo.arguments
|
||||
guard
|
||||
let flagIndex = arguments.firstIndex(of: "--showcaseScene"),
|
||||
arguments.indices.contains(flagIndex + 1)
|
||||
else {
|
||||
return nil as String?
|
||||
}
|
||||
return arguments[flagIndex + 1]
|
||||
}
|
||||
|
||||
Function("prepareShowcaseCapture") {
|
||||
for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
|
||||
SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
|
||||
}
|
||||
}
|
||||
|
||||
Function("markShowcaseReady") { (scene: String) in
|
||||
let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
|
||||
try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
View(T3HeaderButtonView.self) {
|
||||
Prop("label") { (view: T3HeaderButtonView, label: String) in
|
||||
view.setLabel(label)
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
package expo.modules.t3reviewdiff
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.LinearGradient
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Shader
|
||||
import android.graphics.Typeface
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
internal class ReviewDiffCanvasDrawing(context: Context) {
|
||||
private val density = context.resources.displayMetrics.density
|
||||
var theme: DiffTheme = DiffTheme.fallback("light")
|
||||
|
||||
val backgroundPaint = Paint()
|
||||
val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
hinting = Paint.HINTING_ON
|
||||
isSubpixelText = false
|
||||
clearShadowLayer()
|
||||
}
|
||||
val uiPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
hinting = Paint.HINTING_ON
|
||||
isSubpixelText = false
|
||||
clearShadowLayer()
|
||||
}
|
||||
|
||||
private val italicCodeTypeface by lazy {
|
||||
Typeface.create(ReviewDiffTypefaces.regular, Typeface.ITALIC)
|
||||
}
|
||||
private val boldItalicCodeTypeface by lazy {
|
||||
Typeface.create(ReviewDiffTypefaces.bold, Typeface.ITALIC)
|
||||
}
|
||||
|
||||
init {
|
||||
textPaint.typeface = ReviewDiffTypefaces.regular
|
||||
uiPaint.typeface = Typeface.DEFAULT_BOLD
|
||||
}
|
||||
|
||||
fun fileHeaderChevronRect(top: Int, bottom: Int, style: DiffStyle): RectF {
|
||||
val centerY = (top + bottom) / 2f
|
||||
val left = style.fileHeaderHorizontalPaddingPx
|
||||
return RectF(left, centerY - 10f * density, left + 20f * density, centerY + 10f * density)
|
||||
}
|
||||
|
||||
fun fileHeaderIconRect(top: Int, bottom: Int, style: DiffStyle): RectF {
|
||||
val chevron = fileHeaderChevronRect(top, bottom, style)
|
||||
return RectF(
|
||||
chevron.right + 8f * density,
|
||||
chevron.top,
|
||||
chevron.right + 28f * density,
|
||||
chevron.bottom,
|
||||
)
|
||||
}
|
||||
|
||||
fun fileHeaderCheckboxRect(top: Int, bottom: Int, width: Int, style: DiffStyle): RectF {
|
||||
val centerY = (top + bottom) / 2f
|
||||
val right = width - style.fileHeaderHorizontalPaddingPx
|
||||
return RectF(
|
||||
right - 20f * density,
|
||||
centerY - 10f * density,
|
||||
right,
|
||||
centerY + 10f * density,
|
||||
)
|
||||
}
|
||||
|
||||
fun drawDisclosureChevron(
|
||||
canvas: Canvas,
|
||||
rect: RectF,
|
||||
color: Int,
|
||||
collapsed: Boolean
|
||||
) {
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = color
|
||||
borderPaint.strokeWidth = 2f * density
|
||||
borderPaint.strokeCap = Paint.Cap.ROUND
|
||||
borderPaint.strokeJoin = Paint.Join.ROUND
|
||||
val path = Path()
|
||||
if (collapsed) {
|
||||
path.moveTo(rect.left + rect.width() * 0.4f, rect.top + rect.height() * 0.28f)
|
||||
path.lineTo(rect.left + rect.width() * 0.6f, rect.centerY())
|
||||
path.lineTo(rect.left + rect.width() * 0.4f, rect.bottom - rect.height() * 0.28f)
|
||||
} else {
|
||||
path.moveTo(rect.left + rect.width() * 0.28f, rect.top + rect.height() * 0.42f)
|
||||
path.lineTo(rect.centerX(), rect.top + rect.height() * 0.62f)
|
||||
path.lineTo(rect.right - rect.width() * 0.28f, rect.top + rect.height() * 0.42f)
|
||||
}
|
||||
canvas.drawPath(path, borderPaint)
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
}
|
||||
|
||||
fun drawFileIcon(canvas: Canvas, rect: RectF, changeType: String) {
|
||||
val color = when (changeType) {
|
||||
"new" -> theme.addText
|
||||
"deleted" -> theme.deleteText
|
||||
else -> theme.hunkText
|
||||
}
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = color
|
||||
borderPaint.strokeWidth = 2f * density
|
||||
canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint)
|
||||
|
||||
if (changeType == "rename-pure" || changeType == "rename-changed" || changeType == "renamed") {
|
||||
drawRenameChevronIcon(canvas, rect, color)
|
||||
} else {
|
||||
backgroundPaint.color = color
|
||||
canvas.drawCircle(rect.centerX(), rect.centerY(), 3f * density, backgroundPaint)
|
||||
}
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
}
|
||||
|
||||
fun drawViewedCheckbox(canvas: Canvas, rect: RectF, checked: Boolean) {
|
||||
if (checked) {
|
||||
backgroundPaint.color = theme.hunkText
|
||||
canvas.drawRoundRect(rect, 6f * density, 6f * density, backgroundPaint)
|
||||
}
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = if (checked) theme.hunkText else theme.mutedText
|
||||
borderPaint.strokeWidth = 1.8f * density
|
||||
canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint)
|
||||
if (checked) {
|
||||
borderPaint.color = theme.background
|
||||
borderPaint.strokeWidth = 2f * density
|
||||
borderPaint.strokeCap = Paint.Cap.ROUND
|
||||
borderPaint.strokeJoin = Paint.Join.ROUND
|
||||
val path = Path().apply {
|
||||
moveTo(rect.left + rect.width() * 0.28f, rect.centerY())
|
||||
lineTo(rect.left + rect.width() * 0.44f, rect.bottom - rect.height() * 0.3f)
|
||||
lineTo(rect.right - rect.width() * 0.25f, rect.top + rect.height() * 0.3f)
|
||||
}
|
||||
canvas.drawPath(path, borderPaint)
|
||||
}
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
}
|
||||
|
||||
fun drawNoticeIcon(canvas: Canvas, rect: RectF, color: Int) {
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = color
|
||||
borderPaint.strokeWidth = 1.7f * density
|
||||
borderPaint.strokeCap = Paint.Cap.ROUND
|
||||
canvas.drawOval(rect, borderPaint)
|
||||
canvas.drawLine(
|
||||
rect.centerX(),
|
||||
rect.top + rect.height() * 0.3f,
|
||||
rect.centerX(),
|
||||
rect.top + rect.height() * 0.58f,
|
||||
borderPaint,
|
||||
)
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
canvas.drawCircle(rect.centerX(), rect.bottom - rect.height() * 0.24f, density, borderPaint)
|
||||
}
|
||||
|
||||
fun configureUiPaint(paint: Paint, color: Int, size: Float, weight: String) {
|
||||
paint.typeface = if (isBoldFontWeight(weight)) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
|
||||
configureTextPaint(paint, color, size)
|
||||
}
|
||||
|
||||
fun configureMonospacePaint(color: Int, size: Float, weight: String) {
|
||||
textPaint.typeface = ReviewDiffTypefaces.forWeight(weight)
|
||||
configureTextPaint(textPaint, color, size)
|
||||
}
|
||||
|
||||
fun configureCodePaint(color: Int, fontStyle: Int, style: DiffStyle) {
|
||||
val tokenBold = fontStyle and 2 != 0
|
||||
val italic = fontStyle and 1 != 0
|
||||
textPaint.typeface = when {
|
||||
tokenBold && italic -> boldItalicCodeTypeface
|
||||
tokenBold -> ReviewDiffTypefaces.bold
|
||||
italic -> italicCodeTypeface
|
||||
else -> ReviewDiffTypefaces.forWeight(style.codeFontWeight)
|
||||
}
|
||||
configureTextPaint(textPaint, color, style.codeFontSizePx)
|
||||
textPaint.isUnderlineText = fontStyle and 4 != 0
|
||||
}
|
||||
|
||||
fun lineNumberColor(change: String): Int = when (change) {
|
||||
"add" -> theme.addText
|
||||
"delete" -> theme.deleteText
|
||||
else -> theme.mutedText
|
||||
}
|
||||
|
||||
fun drawDeleteStripes(
|
||||
canvas: Canvas,
|
||||
top: Int,
|
||||
bottom: Int,
|
||||
width: Float,
|
||||
color: Int
|
||||
) {
|
||||
backgroundPaint.color = color
|
||||
var y = top.toFloat()
|
||||
while (y < bottom) {
|
||||
canvas.drawRect(0f, y, width, min(bottom.toFloat(), y + density), backgroundPaint)
|
||||
y += 2f * density
|
||||
}
|
||||
}
|
||||
|
||||
fun drawWordDiffRanges(
|
||||
canvas: Canvas,
|
||||
row: DiffRow,
|
||||
codeX: Float,
|
||||
top: Int,
|
||||
bottom: Int
|
||||
) {
|
||||
if (row.wordDiffRanges.isEmpty() || (row.change != "add" && row.change != "delete")) return
|
||||
val color = if (row.change == "add") theme.addBar else theme.deleteBar
|
||||
backgroundPaint.color = withAlpha(color, 71)
|
||||
val characterWidth = textPaint.measureText("M")
|
||||
val fontHeight = textPaint.fontMetrics.run { descent - ascent }
|
||||
val highlightHeight = max(4f * density, min(bottom - top - 4f * density, fontHeight))
|
||||
val highlightTop = (top + bottom - highlightHeight) / 2f
|
||||
row.wordDiffRanges.forEach { range ->
|
||||
val left = codeX + range.start * characterWidth
|
||||
val right = max(left + 2f * density, codeX + range.end * characterWidth)
|
||||
canvas.drawRoundRect(
|
||||
RectF(left, highlightTop, right, highlightTop + highlightHeight),
|
||||
3f * density,
|
||||
3f * density,
|
||||
backgroundPaint,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun drawFileHeaderPathScrollFades(
|
||||
canvas: Canvas,
|
||||
pathRect: RectF,
|
||||
horizontalOffset: Int,
|
||||
maxOffset: Int
|
||||
) {
|
||||
if (maxOffset <= 0 || pathRect.width() <= 0f) return
|
||||
val fadeWidth = min(28f * density, pathRect.width() / 3f)
|
||||
if (horizontalOffset > 0) {
|
||||
drawHorizontalFade(
|
||||
canvas,
|
||||
RectF(pathRect.left, pathRect.top, pathRect.left + fadeWidth, pathRect.bottom),
|
||||
fadesToRight = false,
|
||||
)
|
||||
}
|
||||
if (horizontalOffset < maxOffset) {
|
||||
drawHorizontalFade(
|
||||
canvas,
|
||||
RectF(pathRect.right - fadeWidth, pathRect.top, pathRect.right, pathRect.bottom),
|
||||
fadesToRight = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawRenameChevronIcon(canvas: Canvas, rect: RectF, color: Int) {
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = color
|
||||
borderPaint.strokeWidth = 1.8f * density
|
||||
borderPaint.strokeCap = Paint.Cap.ROUND
|
||||
borderPaint.strokeJoin = Paint.Join.ROUND
|
||||
val chevronWidth = 3.6f * density
|
||||
val chevronHeight = 8f * density
|
||||
val gap = 2.4f * density
|
||||
val startX = rect.centerX() - (chevronWidth * 2f + gap) / 2f
|
||||
val path = Path()
|
||||
for (x in listOf(startX, startX + chevronWidth + gap)) {
|
||||
path.moveTo(x, rect.centerY() - chevronHeight / 2f)
|
||||
path.lineTo(x + chevronWidth, rect.centerY())
|
||||
path.lineTo(x, rect.centerY() + chevronHeight / 2f)
|
||||
}
|
||||
canvas.drawPath(path, borderPaint)
|
||||
}
|
||||
|
||||
private fun configureTextPaint(paint: Paint, color: Int, size: Float) {
|
||||
paint.textSize = size
|
||||
paint.color = color
|
||||
paint.style = Paint.Style.FILL
|
||||
paint.textAlign = Paint.Align.LEFT
|
||||
paint.isUnderlineText = false
|
||||
paint.isFakeBoldText = false
|
||||
paint.clearShadowLayer()
|
||||
}
|
||||
|
||||
private fun drawHorizontalFade(canvas: Canvas, rect: RectF, fadesToRight: Boolean) {
|
||||
val opaque = theme.headerBackground
|
||||
val transparent = Color.argb(0, Color.red(opaque), Color.green(opaque), Color.blue(opaque))
|
||||
backgroundPaint.shader = LinearGradient(
|
||||
rect.left,
|
||||
rect.centerY(),
|
||||
rect.right,
|
||||
rect.centerY(),
|
||||
if (fadesToRight) transparent else opaque,
|
||||
if (fadesToRight) opaque else transparent,
|
||||
Shader.TileMode.CLAMP,
|
||||
)
|
||||
canvas.drawRect(rect, backgroundPaint)
|
||||
backgroundPaint.shader = null
|
||||
}
|
||||
|
||||
private fun isBoldFontWeight(weight: String): Boolean = when (weight.lowercase()) {
|
||||
"medium", "semibold", "semi-bold", "bold", "heavy", "black" -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
private fun withAlpha(color: Int, alpha: Int): Int =
|
||||
Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color))
|
||||
}
|
||||
|
||||
private object ReviewDiffTypefaces {
|
||||
val regular: Typeface = Typeface.create("monospace", Typeface.NORMAL)
|
||||
private val medium: Typeface = Typeface.create("monospace-medium", Typeface.NORMAL)
|
||||
val bold: Typeface = Typeface.create("monospace", Typeface.BOLD)
|
||||
|
||||
fun forWeight(weight: String): Typeface = when (weight.lowercase()) {
|
||||
"medium", "semibold", "semi-bold" -> medium
|
||||
"bold", "heavy", "black" -> bold
|
||||
else -> regular
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.RectF
|
||||
import android.view.GestureDetector
|
||||
import android.view.MotionEvent
|
||||
import android.view.VelocityTracker
|
||||
@@ -19,6 +19,7 @@ import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
@@ -49,12 +50,13 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
private val verticalScroller = OverScroller(context)
|
||||
private val horizontalScroller = OverScroller(context)
|
||||
private var dragAxis: DragAxis? = null
|
||||
private var horizontalDragTarget: HorizontalPanTarget? = null
|
||||
private var lastTouchX = 0f
|
||||
private var lastTouchY = 0f
|
||||
private var velocityTracker: VelocityTracker? = null
|
||||
|
||||
init {
|
||||
canvasView.onRowTap = { row, gesture -> handleRowTap(row, gesture) }
|
||||
canvasView.onRowTap = { row, gesture, target -> handleRowTap(row, gesture, target) }
|
||||
canvasView.onVisibleRowsChanged = { first, last ->
|
||||
onDebug(
|
||||
mapOf(
|
||||
@@ -86,12 +88,13 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
lastVisibleFileId = null
|
||||
pendingInitialScroll = true
|
||||
canvasView.setVerticalOffset(0)
|
||||
canvasView.setHorizontalOffset(0)
|
||||
canvasView.resetHorizontalOffsets()
|
||||
applyPendingInitialScroll()
|
||||
}
|
||||
|
||||
fun setCollapsedFileIdsJson(value: String) {
|
||||
collapsedFileIds = parseStringSet(value)
|
||||
canvasView.collapsedFileIds = collapsedFileIds
|
||||
rebuildVisibleRows()
|
||||
}
|
||||
|
||||
@@ -107,6 +110,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
|
||||
fun setCollapsedCommentIdsJson(value: String) {
|
||||
collapsedCommentIds = parseStringSet(value)
|
||||
canvasView.collapsedCommentIds = collapsedCommentIds
|
||||
rebuildVisibleRows()
|
||||
}
|
||||
|
||||
@@ -202,6 +206,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
verticalScroller.forceFinished(true)
|
||||
horizontalScroller.forceFinished(true)
|
||||
dragAxis = null
|
||||
horizontalDragTarget = canvasView.horizontalPanTarget(event.y)
|
||||
lastTouchX = event.x
|
||||
lastTouchY = event.y
|
||||
parent?.requestDisallowInterceptTouchEvent(true)
|
||||
@@ -212,7 +217,13 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
val deltaX = event.x - lastTouchX
|
||||
val deltaY = event.y - lastTouchY
|
||||
if (max(abs(deltaX), abs(deltaY)) > touchSlop) {
|
||||
dragAxis = if (abs(deltaY) >= abs(deltaX)) DragAxis.VERTICAL else DragAxis.HORIZONTAL
|
||||
dragAxis = if (abs(deltaY) >= abs(deltaX)) {
|
||||
DragAxis.VERTICAL
|
||||
} else {
|
||||
horizontalDragTarget
|
||||
?.takeIf { canvasView.maxHorizontalOffset(it) > 0 }
|
||||
?.let { DragAxis.HORIZONTAL }
|
||||
}
|
||||
}
|
||||
}
|
||||
return dragAxis != null
|
||||
@@ -238,6 +249,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
) {
|
||||
velocityTracker?.recycle()
|
||||
velocityTracker = null
|
||||
horizontalDragTarget = null
|
||||
parent?.requestDisallowInterceptTouchEvent(false)
|
||||
}
|
||||
return handled
|
||||
@@ -253,7 +265,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
if (axis == DragAxis.VERTICAL) {
|
||||
canvasView.scrollByVertical(deltaY)
|
||||
} else {
|
||||
canvasView.scrollByHorizontal(deltaX)
|
||||
horizontalDragTarget?.let { canvasView.scrollByHorizontal(deltaX, it) }
|
||||
}
|
||||
lastTouchX = event.x
|
||||
lastTouchY = event.y
|
||||
@@ -276,7 +288,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
)
|
||||
postInvalidateOnAnimation()
|
||||
}
|
||||
} else {
|
||||
} else if (horizontalDragTarget?.kind == HorizontalPanKind.CODE) {
|
||||
val velocity = -(velocityTracker?.xVelocity ?: 0f).toInt()
|
||||
if (abs(velocity) >= minimumFlingVelocity) {
|
||||
horizontalScroller.fling(
|
||||
@@ -294,6 +306,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
}
|
||||
}
|
||||
dragAxis = null
|
||||
horizontalDragTarget = null
|
||||
velocityTracker?.recycle()
|
||||
velocityTracker = null
|
||||
parent?.requestDisallowInterceptTouchEvent(false)
|
||||
@@ -325,11 +338,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
currentFileCollapsed = collapsedFileIds.contains(row.resolvedFileId)
|
||||
filtered.add(row)
|
||||
} else if (!currentFileCollapsed) {
|
||||
if (row.kind != "comment" || !collapsedCommentIds.contains(row.id)) {
|
||||
filtered.add(row)
|
||||
} else {
|
||||
filtered.add(row.copy(commentText = "Comment collapsed"))
|
||||
}
|
||||
filtered.add(row)
|
||||
}
|
||||
}
|
||||
visibleRows = filtered
|
||||
@@ -339,10 +348,11 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
applyPendingInitialScroll()
|
||||
}
|
||||
|
||||
private fun handleRowTap(row: DiffRow, gesture: String) {
|
||||
private fun handleRowTap(row: DiffRow, gesture: String, target: RowTapTarget) {
|
||||
when (row.kind) {
|
||||
"file" -> {
|
||||
if (gesture == "longPress") {
|
||||
if (gesture != "tap") return
|
||||
if (target == RowTapTarget.VIEWED_CHECKBOX) {
|
||||
onToggleViewedFile(mapOf("fileId" to row.resolvedFileId))
|
||||
} else {
|
||||
onToggleFile(mapOf("fileId" to row.resolvedFileId))
|
||||
@@ -408,7 +418,22 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
|
||||
}
|
||||
}
|
||||
|
||||
private data class DiffRow(
|
||||
private enum class RowTapTarget {
|
||||
ROW,
|
||||
VIEWED_CHECKBOX
|
||||
}
|
||||
|
||||
private enum class HorizontalPanKind {
|
||||
CODE,
|
||||
FILE_HEADER_PATH
|
||||
}
|
||||
|
||||
private data class HorizontalPanTarget(
|
||||
val fileId: String,
|
||||
val kind: HorizontalPanKind
|
||||
)
|
||||
|
||||
internal data class DiffRow(
|
||||
val kind: String,
|
||||
val id: String,
|
||||
val fileId: String,
|
||||
@@ -422,6 +447,7 @@ private data class DiffRow(
|
||||
val change: String,
|
||||
val oldLineNumber: Int?,
|
||||
val newLineNumber: Int?,
|
||||
val wordDiffRanges: List<DiffWordDiffRange>,
|
||||
val commentText: String,
|
||||
val commentRangeLabel: String,
|
||||
val commentSectionTitle: String
|
||||
@@ -429,13 +455,18 @@ private data class DiffRow(
|
||||
val resolvedFileId: String get() = fileId.ifEmpty { id }
|
||||
}
|
||||
|
||||
internal data class DiffWordDiffRange(
|
||||
val start: Int,
|
||||
val end: Int
|
||||
)
|
||||
|
||||
private data class DiffToken(
|
||||
val content: String,
|
||||
val color: Int?,
|
||||
val fontStyle: Int
|
||||
)
|
||||
|
||||
private data class DiffTheme(
|
||||
internal data class DiffTheme(
|
||||
val background: Int,
|
||||
val text: Int,
|
||||
val mutedText: Int,
|
||||
@@ -511,14 +542,25 @@ private data class DiffTheme(
|
||||
}
|
||||
}
|
||||
|
||||
private data class DiffStyle(
|
||||
internal data class DiffStyle(
|
||||
val rowHeightPx: Float,
|
||||
val gutterWidthPx: Float,
|
||||
val codePaddingPx: Float,
|
||||
val changeBarWidthPx: Float,
|
||||
val fileHeaderHeightPx: Float,
|
||||
val fileHeaderHorizontalPaddingPx: Float,
|
||||
val codeFontSizePx: Float,
|
||||
val lineNumberFontSizePx: Float
|
||||
val codeFontWeight: String,
|
||||
val lineNumberFontSizePx: Float,
|
||||
val lineNumberFontWeight: String,
|
||||
val hunkFontSizePx: Float,
|
||||
val hunkFontWeight: String,
|
||||
val fileHeaderFontSizePx: Float,
|
||||
val fileHeaderFontWeight: String,
|
||||
val fileHeaderMetaFontSizePx: Float,
|
||||
val fileHeaderMetaFontWeight: String,
|
||||
val fileHeaderSubtextFontSizePx: Float,
|
||||
val fileHeaderSubtextFontWeight: String
|
||||
) {
|
||||
companion object {
|
||||
fun defaults(density: Float): DiffStyle = DiffStyle(
|
||||
@@ -527,8 +569,19 @@ private data class DiffStyle(
|
||||
codePaddingPx = 10f * density,
|
||||
changeBarWidthPx = 3f * density,
|
||||
fileHeaderHeightPx = 44f * density,
|
||||
fileHeaderHorizontalPaddingPx = 10f * density,
|
||||
codeFontSizePx = 12f * density,
|
||||
codeFontWeight = "regular",
|
||||
lineNumberFontSizePx = 10f * density,
|
||||
lineNumberFontWeight = "regular",
|
||||
hunkFontSizePx = 11f * density,
|
||||
hunkFontWeight = "medium",
|
||||
fileHeaderFontSizePx = 11f * density,
|
||||
fileHeaderFontWeight = "semibold",
|
||||
fileHeaderMetaFontSizePx = 10f * density,
|
||||
fileHeaderMetaFontWeight = "semibold",
|
||||
fileHeaderSubtextFontSizePx = 11f * density,
|
||||
fileHeaderSubtextFontWeight = "medium",
|
||||
)
|
||||
|
||||
fun fromJson(value: String, fallback: DiffStyle, density: Float): DiffStyle = try {
|
||||
@@ -539,11 +592,50 @@ private data class DiffStyle(
|
||||
codePaddingPx = json.floatDp("codePadding", fallback.codePaddingPx, density),
|
||||
changeBarWidthPx = json.floatDp("changeBarWidth", fallback.changeBarWidthPx, density),
|
||||
fileHeaderHeightPx = json.floatDp("fileHeaderHeight", fallback.fileHeaderHeightPx, density),
|
||||
fileHeaderHorizontalPaddingPx = json.floatDp(
|
||||
"fileHeaderHorizontalPadding",
|
||||
fallback.fileHeaderHorizontalPaddingPx,
|
||||
density,
|
||||
),
|
||||
codeFontSizePx = json.floatSp("codeFontSize", fallback.codeFontSizePx, density),
|
||||
codeFontWeight = json.optString("codeFontWeight", fallback.codeFontWeight),
|
||||
lineNumberFontSizePx = json.floatSp(
|
||||
"lineNumberFontSize",
|
||||
fallback.lineNumberFontSizePx,
|
||||
density
|
||||
density,
|
||||
),
|
||||
lineNumberFontWeight = json.optString(
|
||||
"lineNumberFontWeight",
|
||||
fallback.lineNumberFontWeight,
|
||||
),
|
||||
hunkFontSizePx = json.floatSp("hunkFontSize", fallback.hunkFontSizePx, density),
|
||||
hunkFontWeight = json.optString("hunkFontWeight", fallback.hunkFontWeight),
|
||||
fileHeaderFontSizePx = json.floatSp(
|
||||
"fileHeaderFontSize",
|
||||
fallback.fileHeaderFontSizePx,
|
||||
density,
|
||||
),
|
||||
fileHeaderFontWeight = json.optString(
|
||||
"fileHeaderFontWeight",
|
||||
fallback.fileHeaderFontWeight,
|
||||
),
|
||||
fileHeaderMetaFontSizePx = json.floatSp(
|
||||
"fileHeaderMetaFontSize",
|
||||
fallback.fileHeaderMetaFontSizePx,
|
||||
density,
|
||||
),
|
||||
fileHeaderMetaFontWeight = json.optString(
|
||||
"fileHeaderMetaFontWeight",
|
||||
fallback.fileHeaderMetaFontWeight,
|
||||
),
|
||||
fileHeaderSubtextFontSizePx = json.floatSp(
|
||||
"fileHeaderSubtextFontSize",
|
||||
fallback.fileHeaderSubtextFontSizePx,
|
||||
density,
|
||||
),
|
||||
fileHeaderSubtextFontWeight = json.optString(
|
||||
"fileHeaderSubtextFontWeight",
|
||||
fallback.fileHeaderSubtextFontWeight,
|
||||
),
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
@@ -554,35 +646,54 @@ private data class DiffStyle(
|
||||
|
||||
private class DiffCanvasView(context: Context) : View(context) {
|
||||
private val density = resources.displayMetrics.density
|
||||
private val backgroundPaint = Paint()
|
||||
private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { typeface = Typeface.MONOSPACE }
|
||||
private val boldTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
}
|
||||
private val drawing = ReviewDiffCanvasDrawing(context)
|
||||
private val backgroundPaint = drawing.backgroundPaint
|
||||
private val borderPaint = drawing.borderPaint
|
||||
private val textPaint = drawing.textPaint
|
||||
private val boldTextPaint = drawing.uiPaint
|
||||
private val gestureDetector = GestureDetector(
|
||||
context,
|
||||
object : GestureDetector.SimpleOnGestureListener() {
|
||||
override fun onDown(event: MotionEvent): Boolean = true
|
||||
|
||||
override fun onSingleTapUp(event: MotionEvent): Boolean {
|
||||
rowAt(event.y)?.let { onRowTap?.invoke(it, "tap") }
|
||||
rowHitAt(event.y)?.let { hit ->
|
||||
val target = if (
|
||||
hit.row.kind == "file" &&
|
||||
drawing.fileHeaderCheckboxRect(
|
||||
hit.top,
|
||||
hit.bottom,
|
||||
width,
|
||||
style
|
||||
).contains(event.x, event.y)
|
||||
) {
|
||||
RowTapTarget.VIEWED_CHECKBOX
|
||||
} else {
|
||||
RowTapTarget.ROW
|
||||
}
|
||||
onRowTap?.invoke(hit.row, "tap", target)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onLongPress(event: MotionEvent) {
|
||||
rowAt(event.y)?.let { onRowTap?.invoke(it, "longPress") }
|
||||
rowHitAt(event.y)?.row
|
||||
?.takeIf { it.kind == "line" }
|
||||
?.let { onRowTap?.invoke(it, "longPress", RowTapTarget.ROW) }
|
||||
}
|
||||
},
|
||||
)
|
||||
private var rowOffsets = intArrayOf(0)
|
||||
private var verticalOffset = 0
|
||||
private var horizontalOffset = 0
|
||||
private val headerPathOffsetsByFileId = mutableMapOf<String, Int>()
|
||||
private var lastVisibleRange: Pair<Int, Int>? = null
|
||||
|
||||
var rows: List<DiffRow> = emptyList()
|
||||
set(value) {
|
||||
field = value
|
||||
headerPathOffsetsByFileId.keys.retainAll(
|
||||
value.asSequence().filter { it.kind == "file" }.map { it.resolvedFileId }.toSet(),
|
||||
)
|
||||
rebuildOffsets()
|
||||
}
|
||||
var tokensByRowId: Map<String, List<DiffToken>> = emptyMap()
|
||||
@@ -595,6 +706,16 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
var collapsedFileIds: Set<String> = emptySet()
|
||||
set(value) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
var collapsedCommentIds: Set<String> = emptySet()
|
||||
set(value) {
|
||||
field = value
|
||||
rebuildOffsets()
|
||||
}
|
||||
var selectedRowIds: Set<String> = emptySet()
|
||||
set(value) {
|
||||
field = value
|
||||
@@ -603,6 +724,7 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
var theme: DiffTheme = DiffTheme.fallback("light")
|
||||
set(value) {
|
||||
field = value
|
||||
drawing.theme = value
|
||||
invalidate()
|
||||
}
|
||||
var style: DiffStyle = DiffStyle.defaults(density)
|
||||
@@ -614,9 +736,10 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
set(value) {
|
||||
field = max(value, suggestedMinimumWidth)
|
||||
setHorizontalOffset(horizontalOffset)
|
||||
clampHeaderPathOffsets()
|
||||
invalidate()
|
||||
}
|
||||
var onRowTap: ((DiffRow, String) -> Unit)? = null
|
||||
var onRowTap: ((DiffRow, String, RowTapTarget) -> Unit)? = null
|
||||
var onVisibleRowsChanged: ((Int, Int) -> Unit)? = null
|
||||
|
||||
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
||||
@@ -630,6 +753,7 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
super.onSizeChanged(width, height, oldWidth, oldHeight)
|
||||
setVerticalOffset(verticalOffset)
|
||||
setHorizontalOffset(horizontalOffset)
|
||||
clampHeaderPathOffsets()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
@@ -681,27 +805,63 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
invalidate()
|
||||
}
|
||||
|
||||
fun scrollByHorizontal(delta: Int) {
|
||||
setHorizontalOffset(horizontalOffset + delta)
|
||||
fun scrollByHorizontal(delta: Int, target: HorizontalPanTarget) {
|
||||
if (target.kind == HorizontalPanKind.FILE_HEADER_PATH) {
|
||||
setHeaderPathOffset(
|
||||
target.fileId,
|
||||
(headerPathOffsetsByFileId[target.fileId] ?: 0) + delta,
|
||||
)
|
||||
} else {
|
||||
setHorizontalOffset(horizontalOffset + delta)
|
||||
}
|
||||
}
|
||||
|
||||
fun horizontalOffset(): Int = horizontalOffset
|
||||
|
||||
fun maxHorizontalOffset(): Int = max(0, contentWidthPx - width)
|
||||
|
||||
fun maxHorizontalOffset(target: HorizontalPanTarget): Int =
|
||||
if (target.kind == HorizontalPanKind.FILE_HEADER_PATH) {
|
||||
maxHeaderPathOffset(target.fileId)
|
||||
} else {
|
||||
maxHorizontalOffset()
|
||||
}
|
||||
|
||||
fun horizontalPanTarget(y: Float): HorizontalPanTarget? {
|
||||
val row = rowHitAt(y)?.row ?: return null
|
||||
return HorizontalPanTarget(
|
||||
fileId = row.resolvedFileId,
|
||||
kind = if (row.kind == "file") HorizontalPanKind.FILE_HEADER_PATH else HorizontalPanKind.CODE,
|
||||
)
|
||||
}
|
||||
|
||||
fun resetHorizontalOffsets() {
|
||||
setHorizontalOffset(0)
|
||||
if (headerPathOffsetsByFileId.isNotEmpty()) {
|
||||
headerPathOffsetsByFileId.clear()
|
||||
invalidate()
|
||||
}
|
||||
}
|
||||
|
||||
private fun rebuildOffsets() {
|
||||
rowOffsets = IntArray(rows.size + 1)
|
||||
rows.forEachIndexed { index, row ->
|
||||
rowOffsets[index + 1] = rowOffsets[index] + rowHeight(row)
|
||||
}
|
||||
setVerticalOffset(verticalOffset)
|
||||
clampHeaderPathOffsets()
|
||||
requestLayout()
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun rowHeight(row: DiffRow): Int = when (row.kind) {
|
||||
"file" -> style.fileHeaderHeightPx.toInt()
|
||||
"comment" -> max((style.rowHeightPx * 3.2f).toInt(), (56 * density).toInt())
|
||||
"notice" -> max((style.rowHeightPx * 2f).toInt(), (44 * density).toInt())
|
||||
"comment" -> if (collapsedCommentIds.contains(row.id)) {
|
||||
(44 * density).toInt()
|
||||
} else {
|
||||
(124 * density).toInt()
|
||||
}
|
||||
else -> style.rowHeightPx.toInt()
|
||||
}.coerceAtLeast(1)
|
||||
|
||||
@@ -721,13 +881,20 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
return low.coerceIn(0, rows.lastIndex)
|
||||
}
|
||||
|
||||
private fun rowAt(y: Float): DiffRow? {
|
||||
private fun rowHitAt(y: Float): RowHit? {
|
||||
stickyFileHeader(firstVisibleRow())?.let { sticky ->
|
||||
if (y >= max(0, sticky.top).toFloat() && y < sticky.bottom.toFloat()) {
|
||||
return rows.getOrNull(sticky.index)
|
||||
return rows.getOrNull(sticky.index)?.let { RowHit(it, sticky.top, sticky.bottom) }
|
||||
}
|
||||
}
|
||||
return rows.getOrNull(rowIndexAt(verticalOffset + y.toInt()))
|
||||
val index = rowIndexAt(verticalOffset + y.toInt())
|
||||
return rows.getOrNull(index)?.let {
|
||||
RowHit(
|
||||
row = it,
|
||||
top = rowOffsets[index] - verticalOffset,
|
||||
bottom = rowOffsets[index + 1] - verticalOffset,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun firstVisibleRow(): Int = rowIndexAt(verticalOffset)
|
||||
@@ -754,23 +921,140 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
|
||||
private fun drawFileRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
fill(canvas, theme.headerBackground, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
val baseline = centeredBaseline(top, bottom, boldTextPaint.apply { textSize = 13f * density })
|
||||
boldTextPaint.color = theme.text
|
||||
val marker = if (viewedFileIds.contains(row.resolvedFileId)) "[x] " else "[ ] "
|
||||
textPaint.color = theme.mutedText
|
||||
textPaint.textSize = 11f * density
|
||||
val stats = "+${row.additions} -${row.deletions}"
|
||||
val statsX = max(12f * density, width - textPaint.measureText(stats) - 16f * density)
|
||||
val title = ellipsize(marker + row.filePath, boldTextPaint, statsX - 28f * density)
|
||||
canvas.drawText(title, 12f * density, baseline, boldTextPaint)
|
||||
canvas.drawText(stats, statsX, baseline, textPaint)
|
||||
|
||||
val chevronRect = drawing.fileHeaderChevronRect(top, bottom, style)
|
||||
val iconRect = drawing.fileHeaderIconRect(top, bottom, style)
|
||||
val checkboxRect = drawing.fileHeaderCheckboxRect(top, bottom, width, style)
|
||||
drawing.drawDisclosureChevron(
|
||||
canvas,
|
||||
chevronRect,
|
||||
theme.mutedText,
|
||||
collapsed = collapsedFileIds.contains(row.resolvedFileId),
|
||||
)
|
||||
drawing.drawFileIcon(canvas, iconRect, row.changeType)
|
||||
drawing.drawViewedCheckbox(
|
||||
canvas,
|
||||
checkboxRect,
|
||||
viewedFileIds.contains(row.resolvedFileId),
|
||||
)
|
||||
|
||||
drawing.configureUiPaint(
|
||||
paint = boldTextPaint,
|
||||
color = theme.deleteText,
|
||||
size = style.fileHeaderMetaFontSizePx,
|
||||
weight = style.fileHeaderMetaFontWeight,
|
||||
)
|
||||
val deleteText = "-${row.deletions}"
|
||||
val deleteWidth = boldTextPaint.measureText(deleteText)
|
||||
val addText = "+${row.additions}"
|
||||
val addWidth = boldTextPaint.measureText(addText)
|
||||
val countGap = 4f * density
|
||||
val countsX = checkboxRect.left - 10f * density - deleteWidth - countGap - addWidth
|
||||
val baseline = centeredBaseline(top, bottom, boldTextPaint)
|
||||
canvas.drawText(deleteText, countsX, baseline, boldTextPaint)
|
||||
boldTextPaint.color = theme.addText
|
||||
canvas.drawText(addText, countsX + deleteWidth + countGap, baseline, boldTextPaint)
|
||||
|
||||
val pathLayout = fileHeaderPathLayout(row, top, bottom, iconRect, countsX)
|
||||
val maxPathOffset = maxHeaderPathOffset(pathLayout)
|
||||
val pathOffset = (headerPathOffsetsByFileId[row.resolvedFileId] ?: 0)
|
||||
.coerceIn(0, maxPathOffset)
|
||||
canvas.save()
|
||||
canvas.clipRect(pathLayout.rect)
|
||||
canvas.drawText(
|
||||
pathLayout.displayPath,
|
||||
pathLayout.rect.left - pathOffset,
|
||||
centeredBaseline(top, bottom, boldTextPaint),
|
||||
boldTextPaint,
|
||||
)
|
||||
canvas.restore()
|
||||
drawing.drawFileHeaderPathScrollFades(
|
||||
canvas,
|
||||
pathLayout.rect,
|
||||
pathOffset,
|
||||
maxPathOffset,
|
||||
)
|
||||
drawBottomBorder(canvas, bottom)
|
||||
}
|
||||
|
||||
private fun fileHeaderPathLayout(
|
||||
row: DiffRow,
|
||||
top: Int,
|
||||
bottom: Int,
|
||||
iconRect: RectF,
|
||||
countsX: Float
|
||||
): FileHeaderPathLayout {
|
||||
drawing.configureUiPaint(
|
||||
paint = boldTextPaint,
|
||||
color = theme.text,
|
||||
size = style.fileHeaderFontSizePx,
|
||||
weight = style.fileHeaderFontWeight,
|
||||
)
|
||||
val pathX = iconRect.right + 10f * density
|
||||
val pathWidth = max(24f * density, countsX - pathX - 12f * density)
|
||||
val centerY = (top + bottom) / 2f
|
||||
val displayPath = if (
|
||||
!row.previousPath.isNullOrEmpty() && row.previousPath != row.filePath
|
||||
) {
|
||||
"${row.previousPath} -> ${row.filePath}"
|
||||
} else {
|
||||
row.filePath
|
||||
}
|
||||
return FileHeaderPathLayout(
|
||||
displayPath = displayPath,
|
||||
rect = RectF(pathX, centerY - 10f * density, pathX + pathWidth, centerY + 10f * density),
|
||||
)
|
||||
}
|
||||
|
||||
private fun maxHeaderPathOffset(fileId: String): Int {
|
||||
val row = rows.firstOrNull { it.kind == "file" && it.resolvedFileId == fileId } ?: return 0
|
||||
val top = 0
|
||||
val bottom = rowHeight(row)
|
||||
val iconRect = drawing.fileHeaderIconRect(top, bottom, style)
|
||||
val checkboxRect = drawing.fileHeaderCheckboxRect(top, bottom, width, style)
|
||||
drawing.configureUiPaint(
|
||||
paint = boldTextPaint,
|
||||
color = theme.deleteText,
|
||||
size = style.fileHeaderMetaFontSizePx,
|
||||
weight = style.fileHeaderMetaFontWeight,
|
||||
)
|
||||
val countsX = checkboxRect.left - 10f * density -
|
||||
boldTextPaint.measureText("-${row.deletions}") - 4f * density -
|
||||
boldTextPaint.measureText("+${row.additions}")
|
||||
return maxHeaderPathOffset(fileHeaderPathLayout(row, top, bottom, iconRect, countsX))
|
||||
}
|
||||
|
||||
private fun maxHeaderPathOffset(layout: FileHeaderPathLayout): Int = max(
|
||||
0,
|
||||
ceil(boldTextPaint.measureText(layout.displayPath) - layout.rect.width()).toInt(),
|
||||
)
|
||||
|
||||
private fun setHeaderPathOffset(fileId: String, value: Int) {
|
||||
val nextOffset = value.coerceIn(0, maxHeaderPathOffset(fileId))
|
||||
if ((headerPathOffsetsByFileId[fileId] ?: 0) == nextOffset) return
|
||||
headerPathOffsetsByFileId[fileId] = nextOffset
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun clampHeaderPathOffsets() {
|
||||
headerPathOffsetsByFileId.keys.toList().forEach { fileId ->
|
||||
val nextOffset = (headerPathOffsetsByFileId[fileId] ?: 0)
|
||||
.coerceIn(0, maxHeaderPathOffset(fileId))
|
||||
if (nextOffset == 0) {
|
||||
headerPathOffsetsByFileId.remove(fileId)
|
||||
} else {
|
||||
headerPathOffsetsByFileId[fileId] = nextOffset
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawHunkRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
fill(canvas, theme.hunkBackground, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
textPaint.color = theme.hunkText
|
||||
textPaint.textSize = style.codeFontSizePx
|
||||
drawing.configureMonospacePaint(
|
||||
color = theme.hunkText,
|
||||
size = style.hunkFontSizePx,
|
||||
weight = style.hunkFontWeight,
|
||||
)
|
||||
drawScrollableCode(canvas, top, bottom) { codeX ->
|
||||
canvas.drawText(
|
||||
row.text.ifEmpty { row.content },
|
||||
@@ -782,36 +1066,82 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
}
|
||||
|
||||
private fun drawNoticeRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
textPaint.color = theme.mutedText
|
||||
textPaint.textSize = style.codeFontSizePx
|
||||
drawScrollableCode(canvas, top, bottom) { codeX ->
|
||||
canvas.drawText(row.text, codeX, centeredBaseline(top, bottom, textPaint), textPaint)
|
||||
}
|
||||
fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
val iconSize = 16f * density
|
||||
val iconRect = RectF(
|
||||
style.fileHeaderHorizontalPaddingPx + 2f * density,
|
||||
(top + bottom - iconSize) / 2f,
|
||||
style.fileHeaderHorizontalPaddingPx + 2f * density + iconSize,
|
||||
(top + bottom + iconSize) / 2f,
|
||||
)
|
||||
drawing.drawNoticeIcon(canvas, iconRect, theme.mutedText)
|
||||
drawing.configureUiPaint(
|
||||
paint = textPaint,
|
||||
color = theme.mutedText,
|
||||
size = style.fileHeaderSubtextFontSizePx,
|
||||
weight = style.fileHeaderSubtextFontWeight,
|
||||
)
|
||||
val textX = iconRect.right + 10f * density
|
||||
canvas.drawText(
|
||||
ellipsize(row.text, textPaint, width - textX - style.fileHeaderHorizontalPaddingPx),
|
||||
textX,
|
||||
centeredBaseline(top, bottom, textPaint),
|
||||
textPaint,
|
||||
)
|
||||
drawBottomBorder(canvas, bottom)
|
||||
}
|
||||
|
||||
private fun drawCommentRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
fill(
|
||||
canvas,
|
||||
theme.headerBackground,
|
||||
style.gutterWidthPx,
|
||||
top.toFloat(),
|
||||
width.toFloat(),
|
||||
bottom.toFloat()
|
||||
fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
val cardRect = RectF(
|
||||
8f * density,
|
||||
top + 5f * density,
|
||||
width - 8f * density,
|
||||
bottom - 5f * density,
|
||||
)
|
||||
boldTextPaint.color = theme.text
|
||||
boldTextPaint.textSize = 12f * density
|
||||
drawScrollableCode(canvas, top, bottom) { codeX ->
|
||||
backgroundPaint.color = theme.headerBackground
|
||||
canvas.drawRoundRect(cardRect, 10f * density, 10f * density, backgroundPaint)
|
||||
borderPaint.style = Paint.Style.STROKE
|
||||
borderPaint.color = withAlpha(theme.border, 217)
|
||||
borderPaint.strokeWidth = density
|
||||
canvas.drawRoundRect(cardRect, 10f * density, 10f * density, borderPaint)
|
||||
borderPaint.style = Paint.Style.FILL
|
||||
|
||||
val collapsed = collapsedCommentIds.contains(row.id)
|
||||
val chevronRect = RectF(
|
||||
cardRect.left + 10f * density,
|
||||
cardRect.top + 11f * density,
|
||||
cardRect.left + 26f * density,
|
||||
cardRect.top + 27f * density,
|
||||
)
|
||||
drawing.drawDisclosureChevron(canvas, chevronRect, theme.mutedText, collapsed)
|
||||
drawing.configureUiPaint(
|
||||
paint = textPaint,
|
||||
color = theme.mutedText,
|
||||
size = style.fileHeaderSubtextFontSizePx,
|
||||
weight = style.fileHeaderSubtextFontWeight,
|
||||
)
|
||||
val title = "Comment on ${row.commentRangeLabel.ifEmpty { "line" }}"
|
||||
canvas.drawText(
|
||||
ellipsize(title, textPaint, cardRect.right - chevronRect.right - 20f * density),
|
||||
chevronRect.right + 10f * density,
|
||||
cardRect.top + 22f * density,
|
||||
textPaint,
|
||||
)
|
||||
if (!collapsed) {
|
||||
textPaint.color = theme.text
|
||||
val bodyX = cardRect.left + 18f * density
|
||||
canvas.drawText(
|
||||
row.commentSectionTitle.ifEmpty { row.commentRangeLabel.ifEmpty { "Comment" } },
|
||||
codeX,
|
||||
top + 20f * density,
|
||||
boldTextPaint,
|
||||
ellipsize(
|
||||
row.commentText.ifEmpty { "Comment" },
|
||||
textPaint,
|
||||
cardRect.right - bodyX - 18f * density
|
||||
),
|
||||
bodyX,
|
||||
cardRect.top + 58f * density,
|
||||
textPaint,
|
||||
)
|
||||
textPaint.color = theme.mutedText
|
||||
textPaint.textSize = 12f * density
|
||||
canvas.drawText(row.commentText, codeX, top + 42f * density, textPaint)
|
||||
}
|
||||
drawBottomBorder(canvas, bottom)
|
||||
}
|
||||
|
||||
@Suppress("CyclomaticComplexMethod")
|
||||
@@ -822,65 +1152,79 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
else -> theme.background
|
||||
}
|
||||
fill(canvas, background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat())
|
||||
if (style.changeBarWidthPx > 0) {
|
||||
when (row.change) {
|
||||
"add" -> fill(
|
||||
canvas,
|
||||
theme.addBar,
|
||||
0f,
|
||||
top.toFloat(),
|
||||
style.changeBarWidthPx,
|
||||
bottom.toFloat()
|
||||
)
|
||||
"delete" -> drawing.drawDeleteStripes(
|
||||
canvas,
|
||||
top,
|
||||
bottom,
|
||||
style.changeBarWidthPx,
|
||||
theme.deleteBar,
|
||||
)
|
||||
}
|
||||
}
|
||||
val selected = selectedRowIds.contains(row.id)
|
||||
if (selected) {
|
||||
fill(
|
||||
canvas,
|
||||
withAlpha(theme.hunkText, if (theme.background == Color.WHITE) 54 else 76),
|
||||
withAlpha(theme.hunkText, 56),
|
||||
0f,
|
||||
top.toFloat(),
|
||||
width.toFloat(),
|
||||
bottom.toFloat(),
|
||||
)
|
||||
}
|
||||
val barColor = when (row.change) {
|
||||
"add" -> theme.addBar
|
||||
"delete" -> theme.deleteBar
|
||||
else -> Color.TRANSPARENT
|
||||
}
|
||||
if (barColor != Color.TRANSPARENT && style.changeBarWidthPx > 0) {
|
||||
fill(canvas, barColor, 0f, top.toFloat(), style.changeBarWidthPx, bottom.toFloat())
|
||||
fill(
|
||||
canvas,
|
||||
withAlpha(theme.hunkText, 242),
|
||||
0f,
|
||||
top.toFloat(),
|
||||
style.changeBarWidthPx,
|
||||
bottom.toFloat()
|
||||
)
|
||||
}
|
||||
|
||||
val tokens = tokensByRowId[row.id]
|
||||
drawScrollableCode(canvas, top, bottom) { codeX ->
|
||||
drawing.configureCodePaint(theme.text, 0, style)
|
||||
drawing.drawWordDiffRanges(canvas, row, codeX, top, bottom)
|
||||
if (tokens.isNullOrEmpty()) {
|
||||
textPaint.textSize = style.codeFontSizePx
|
||||
textPaint.color = when (row.change) {
|
||||
"add" -> theme.addText
|
||||
"delete" -> theme.deleteText
|
||||
else -> theme.text
|
||||
}
|
||||
canvas.drawText(row.content, codeX, centeredBaseline(top, bottom, textPaint), textPaint)
|
||||
} else {
|
||||
var x = codeX
|
||||
tokens.forEach { token ->
|
||||
textPaint.textSize = style.codeFontSizePx
|
||||
textPaint.color = token.color ?: theme.text
|
||||
textPaint.typeface = when {
|
||||
token.fontStyle and 1 != 0 -> Typeface.create(Typeface.MONOSPACE, Typeface.ITALIC)
|
||||
token.fontStyle and 2 != 0 -> Typeface.create(Typeface.MONOSPACE, Typeface.BOLD)
|
||||
else -> Typeface.MONOSPACE
|
||||
}
|
||||
drawing.configureCodePaint(token.color ?: theme.text, token.fontStyle, style)
|
||||
canvas.drawText(token.content, x, centeredBaseline(top, bottom, textPaint), textPaint)
|
||||
x += textPaint.measureText(token.content)
|
||||
}
|
||||
textPaint.typeface = Typeface.MONOSPACE
|
||||
}
|
||||
}
|
||||
|
||||
textPaint.textSize = style.lineNumberFontSizePx
|
||||
textPaint.color = if (selected) theme.text else theme.mutedText
|
||||
val oldNumber = row.oldLineNumber?.toString().orEmpty()
|
||||
val newNumber = row.newLineNumber?.toString().orEmpty()
|
||||
val baseline = centeredBaseline(top, bottom, textPaint)
|
||||
canvas.drawText(oldNumber, style.changeBarWidthPx + 6f * density, baseline, textPaint)
|
||||
canvas.drawText(
|
||||
newNumber,
|
||||
style.changeBarWidthPx + style.gutterWidthPx / 2f,
|
||||
baseline,
|
||||
textPaint
|
||||
drawLineNumber(canvas, row, top, bottom)
|
||||
}
|
||||
|
||||
private fun drawLineNumber(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) {
|
||||
val lineNumber = row.newLineNumber ?: row.oldLineNumber ?: return
|
||||
drawing.configureMonospacePaint(
|
||||
color = drawing.lineNumberColor(row.change),
|
||||
size = style.lineNumberFontSizePx,
|
||||
weight = style.lineNumberFontWeight,
|
||||
)
|
||||
textPaint.textAlign = Paint.Align.RIGHT
|
||||
canvas.drawText(
|
||||
lineNumber.toString(),
|
||||
style.changeBarWidthPx + style.gutterWidthPx - style.codePaddingPx,
|
||||
centeredBaseline(top, bottom, textPaint),
|
||||
textPaint,
|
||||
)
|
||||
textPaint.textAlign = Paint.Align.LEFT
|
||||
}
|
||||
|
||||
private fun drawScrollableCode(
|
||||
@@ -972,6 +1316,17 @@ private class DiffCanvasView(context: Context) : View(context) {
|
||||
val top: Int,
|
||||
val bottom: Int
|
||||
)
|
||||
|
||||
private data class RowHit(
|
||||
val row: DiffRow,
|
||||
val top: Int,
|
||||
val bottom: Int
|
||||
)
|
||||
|
||||
private data class FileHeaderPathLayout(
|
||||
val displayPath: String,
|
||||
val rect: RectF
|
||||
)
|
||||
}
|
||||
|
||||
private fun withAlpha(color: Int, alpha: Int): Int =
|
||||
@@ -995,6 +1350,7 @@ private fun parseRows(value: String): List<DiffRow> = try {
|
||||
change = row.optString("change", "context"),
|
||||
oldLineNumber = row.optNullableInt("oldLineNumber"),
|
||||
newLineNumber = row.optNullableInt("newLineNumber"),
|
||||
wordDiffRanges = row.optJSONArray("wordDiffRanges")?.let(::parseWordDiffRanges).orEmpty(),
|
||||
commentText = row.optString("commentText"),
|
||||
commentRangeLabel = row.optString("commentRangeLabel"),
|
||||
commentSectionTitle = row.optString("commentSectionTitle"),
|
||||
@@ -1004,6 +1360,17 @@ private fun parseRows(value: String): List<DiffRow> = try {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
private fun parseWordDiffRanges(value: JSONArray): List<DiffWordDiffRange> = buildList {
|
||||
for (index in 0 until value.length()) {
|
||||
val range = value.optJSONObject(index) ?: continue
|
||||
val start = range.optInt("start", -1)
|
||||
val end = range.optInt("end", -1)
|
||||
if (start >= 0 && end > start) {
|
||||
add(DiffWordDiffRange(start = start, end = end))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseTokensObject(value: String): Map<String, List<DiffToken>> = try {
|
||||
parseTokensObject(JSONObject(value))
|
||||
} catch (_: Exception) {
|
||||
@@ -1020,7 +1387,7 @@ private fun parseTokensObject(value: JSONObject): Map<String, List<DiffToken>> {
|
||||
val token = array.getJSONObject(index)
|
||||
DiffToken(
|
||||
content = token.optString("content"),
|
||||
color = token.optNullableString("color")?.let { parseColor(it, Color.TRANSPARENT) },
|
||||
color = token.optNullableString("color")?.let(::parseColorOrNull),
|
||||
fontStyle = token.optInt("fontStyle"),
|
||||
)
|
||||
}
|
||||
@@ -1043,6 +1410,12 @@ private fun parseColor(value: String, fallback: Int): Int = try {
|
||||
fallback
|
||||
}
|
||||
|
||||
private fun parseColorOrNull(value: String): Int? = try {
|
||||
Color.parseColor(value)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
private fun JSONObject.optNullableString(key: String): String? =
|
||||
if (isNull(key)) null else optString(key).takeIf { it.isNotEmpty() }
|
||||
|
||||
|
||||
@@ -30,6 +30,10 @@ class T3TerminalModule : Module() {
|
||||
view.focusRequest = focusRequest
|
||||
}
|
||||
|
||||
Prop("autoFocus") { view: T3TerminalView, autoFocus: Boolean ->
|
||||
view.autoFocus = autoFocus
|
||||
}
|
||||
|
||||
Prop("appearanceScheme") { view: T3TerminalView, appearanceScheme: String ->
|
||||
view.appearanceScheme = appearanceScheme
|
||||
}
|
||||
|
||||
@@ -76,6 +76,17 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
|
||||
}
|
||||
}
|
||||
|
||||
var autoFocus: Boolean = true
|
||||
set(value) {
|
||||
field = value
|
||||
if (value) {
|
||||
requestKeyboardFocus()
|
||||
} else {
|
||||
inputView.clearFocus()
|
||||
hideKeyboard()
|
||||
}
|
||||
}
|
||||
|
||||
var backgroundColorHex: String = "#24292E"
|
||||
set(value) {
|
||||
field = value
|
||||
@@ -368,6 +379,13 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
|
||||
inputMethodManager?.showSoftInput(inputView, InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
|
||||
private fun hideKeyboard() {
|
||||
val inputMethodManager = context.getSystemService(
|
||||
Context.INPUT_METHOD_SERVICE
|
||||
) as? InputMethodManager
|
||||
inputMethodManager?.hideSoftInputFromWindow(windowToken, 0)
|
||||
}
|
||||
|
||||
private fun applyTheme() {
|
||||
setBackgroundColor(backgroundColorValue)
|
||||
container.setBackgroundColor(backgroundColorValue)
|
||||
|
||||
@@ -7,7 +7,7 @@ public class T3TerminalModule: Module {
|
||||
// Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
|
||||
// logs so a stale native binary is distinguishable from a broken key pipeline.
|
||||
Constants([
|
||||
"hardwareKeyRevision": 2,
|
||||
"hardwareKeyRevision": 3,
|
||||
])
|
||||
|
||||
View(T3TerminalView.self) {
|
||||
@@ -27,6 +27,10 @@ public class T3TerminalModule: Module {
|
||||
view.focusRequest = focusRequest
|
||||
}
|
||||
|
||||
Prop("autoFocus") { (view: T3TerminalView, autoFocus: Bool) in
|
||||
view.autoFocus = autoFocus
|
||||
}
|
||||
|
||||
Prop("appearanceScheme") { (view: T3TerminalView, appearanceScheme: String) in
|
||||
view.appearanceScheme = appearanceScheme
|
||||
}
|
||||
|
||||
@@ -119,6 +119,21 @@ private enum TerminalHardwareKeyEncoder {
|
||||
}
|
||||
}
|
||||
|
||||
private enum TerminalInputSequence {
|
||||
/// Terminal Enter is carriage return. Sending line feed instead is Ctrl+J,
|
||||
/// which raw-mode TUIs may interpret as the literal J key.
|
||||
static let carriageReturn = "\r"
|
||||
|
||||
static func normalizingReturn(_ input: String) -> String {
|
||||
switch input {
|
||||
case "\n", "\r\n":
|
||||
return carriageReturn
|
||||
default:
|
||||
return input
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class TerminalInputField: UITextField {
|
||||
var onDeleteBackward: (() -> Void)?
|
||||
var onInsert: ((String) -> Void)?
|
||||
@@ -233,6 +248,17 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
var autoFocus = true {
|
||||
didSet {
|
||||
guard oldValue != autoFocus else { return }
|
||||
if autoFocus {
|
||||
requestKeyboardFocus()
|
||||
} else {
|
||||
inputField.resignFirstResponder()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue {
|
||||
didSet {
|
||||
guard oldValue != appearanceScheme else { return }
|
||||
@@ -344,7 +370,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
public override func didMoveToWindow() {
|
||||
super.didMoveToWindow()
|
||||
|
||||
guard window != nil else { return }
|
||||
guard window != nil, autoFocus else { return }
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.requestKeyboardFocus()
|
||||
}
|
||||
@@ -352,7 +378,9 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
|
||||
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
|
||||
if !string.isEmpty {
|
||||
emitInput(string)
|
||||
// Some software keyboards deliver Return through this delegate instead of
|
||||
// textFieldShouldReturn, so normalize that path too.
|
||||
emitInput(TerminalInputSequence.normalizingReturn(string))
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -360,7 +388,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
}
|
||||
|
||||
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
|
||||
emitInput("\n")
|
||||
emitInput(TerminalInputSequence.carriageReturn)
|
||||
textField.text = ""
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -5,12 +5,14 @@
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
"dev": "expo start --clear",
|
||||
"dev:client": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear --localhost",
|
||||
"dev:client": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear --lan",
|
||||
"dev:client:preview": "eas env:exec preview 'EXPO_NO_DOTENV=1 APP_VARIANT=preview expo start --dev-client --scheme t3code-preview --clear --lan'",
|
||||
"start": "expo start",
|
||||
"start:dev": "APP_VARIANT=development expo start",
|
||||
"start:preview": "APP_VARIANT=preview expo start",
|
||||
"start:prod": "APP_VARIANT=production expo start",
|
||||
"showcase": "APP_VARIANT=development EXPO_PUBLIC_SHOWCASE=1 expo start --dev-client --scheme t3code-dev --clear",
|
||||
"screenshots": "node ../../scripts/mobile-showcase.ts",
|
||||
"android": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
|
||||
"android:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && REACT_NATIVE_PACKAGER_HOSTNAME=localhost expo run:android",
|
||||
"android:preview": "APP_VARIANT=preview EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
|
||||
@@ -91,6 +93,7 @@
|
||||
"expo-paste-input": "^0.1.15",
|
||||
"expo-quick-actions": "^6.0.2",
|
||||
"expo-secure-store": "~56.0.4",
|
||||
"expo-sharing": "~56.0.18",
|
||||
"expo-splash-screen": "~56.0.10",
|
||||
"expo-sqlite": "~56.0.5",
|
||||
"expo-symbols": "~56.0.6",
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"use strict";
|
||||
|
||||
// expo-sharing intentionally uses a fixed target name and also uses that
|
||||
// internal target name as CFBundleDisplayName. Brand the extension while
|
||||
// leaving its initially-empty signing team intact: Expo uses that state to
|
||||
// select ios.appleTeamId and enable first-time profile provisioning.
|
||||
//
|
||||
// ORDERING: list this plugin BEFORE expo-sharing. Expo runs same-type mods in
|
||||
// reverse registration order, so this executes after the extension exists.
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { withDangerousMod, withXcodeProject } = require("expo/config-plugins");
|
||||
|
||||
const TARGET_NAME = "expo-sharing-extension";
|
||||
|
||||
function stripComments(section) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(section ?? {}).filter(([key]) => !key.endsWith("_comment")),
|
||||
);
|
||||
}
|
||||
|
||||
function findByName(section, name) {
|
||||
return Object.entries(stripComments(section)).find(([, value]) => value?.name === name) ?? null;
|
||||
}
|
||||
|
||||
function escapeXml(value) {
|
||||
return value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'");
|
||||
}
|
||||
|
||||
function withDisplayNamePlist(config, displayName) {
|
||||
return withDangerousMod(config, [
|
||||
"ios",
|
||||
(cfg) => {
|
||||
const plistPath = path.join(cfg.modRequest.platformProjectRoot, TARGET_NAME, "Info.plist");
|
||||
if (!fs.existsSync(plistPath)) {
|
||||
throw new Error(
|
||||
`${TARGET_NAME}/Info.plist was not generated. Register withShareExtensionDisplayName before expo-sharing.`,
|
||||
);
|
||||
}
|
||||
const source = fs.readFileSync(plistPath, "utf8");
|
||||
const displayNamePattern = /(<key>CFBundleDisplayName<\/key>\s*<string>)[^<]*(<\/string>)/;
|
||||
if (!displayNamePattern.test(source)) {
|
||||
throw new Error(`Could not update CFBundleDisplayName in ${plistPath}.`);
|
||||
}
|
||||
const next = source.replace(displayNamePattern, `$1${escapeXml(displayName)}$2`);
|
||||
if (next !== source) {
|
||||
fs.writeFileSync(plistPath, next);
|
||||
}
|
||||
return cfg;
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function withExtensionDisplayNameBuildSetting(config, displayName) {
|
||||
return withXcodeProject(config, (cfg) => {
|
||||
const objects = cfg.modResults.hash.project.objects;
|
||||
const targetEntry = findByName(objects.PBXNativeTarget, TARGET_NAME);
|
||||
if (!targetEntry) {
|
||||
throw new Error(
|
||||
`${TARGET_NAME} Xcode target was not generated. Register withShareExtensionDisplayName before expo-sharing.`,
|
||||
);
|
||||
}
|
||||
const target = targetEntry[1];
|
||||
const configurationList = stripComments(objects.XCConfigurationList)[
|
||||
target.buildConfigurationList
|
||||
];
|
||||
if (!configurationList) {
|
||||
throw new Error(`Could not find build configurations for ${TARGET_NAME}.`);
|
||||
}
|
||||
const buildConfigurations = stripComments(objects.XCBuildConfiguration);
|
||||
for (const reference of configurationList.buildConfigurations ?? []) {
|
||||
const buildConfiguration = buildConfigurations[reference.value];
|
||||
if (buildConfiguration?.buildSettings) {
|
||||
buildConfiguration.buildSettings.INFOPLIST_KEY_CFBundleDisplayName = `"${displayName}"`;
|
||||
}
|
||||
}
|
||||
return cfg;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = function withShareExtensionDisplayName(config) {
|
||||
const displayName = config.name;
|
||||
return withExtensionDisplayNameBuildSetting(
|
||||
withDisplayNamePlist(config, displayName),
|
||||
displayName,
|
||||
);
|
||||
};
|
||||
@@ -11,6 +11,8 @@ import { createStaticNavigation, DarkTheme, DefaultTheme } from "@react-navigati
|
||||
import { RegistryContext } from "@effect/atom-react";
|
||||
import { ConfirmDialogHost } from "./components/ConfirmDialogHost";
|
||||
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
|
||||
import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
|
||||
import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";
|
||||
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import { RootStack } from "./Stack";
|
||||
import { appAtomRegistry } from "./state/atom-registry";
|
||||
@@ -20,13 +22,20 @@ import { useThemeColor } from "./lib/useThemeColor";
|
||||
|
||||
import "../global.css";
|
||||
|
||||
if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
|
||||
prepareNativeShowcaseCapture();
|
||||
}
|
||||
|
||||
const appLinking = {
|
||||
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
|
||||
// The Expo dev client launches the app via
|
||||
// <scheme>://expo-development-client/?url=<packager> — that URL addresses
|
||||
// the launcher, not app navigation. Without this filter it falls through
|
||||
// to the NotFound wildcard route on every dev launch.
|
||||
filter: (url: string) => !url.includes("expo-development-client"),
|
||||
// expo-sharing uses a private lifecycle URL only to wake the app. The
|
||||
// persisted share inbox below owns navigation once the payload is durable.
|
||||
filter: (url: string) =>
|
||||
!url.includes("expo-development-client") && !url.includes("://expo-sharing"),
|
||||
};
|
||||
|
||||
const Navigation = createStaticNavigation(RootStack);
|
||||
@@ -58,10 +67,12 @@ export default function App() {
|
||||
the system is in dark mode. */}
|
||||
{/* Blur target for Android dropdown backdrops — see appBlurTarget.ts. */}
|
||||
<BlurTargetView ref={appBlurTargetRef} style={{ flex: 1 }}>
|
||||
<Navigation
|
||||
linking={appLinking}
|
||||
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
|
||||
/>
|
||||
<IncomingShareProvider>
|
||||
<Navigation
|
||||
linking={appLinking}
|
||||
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
|
||||
/>
|
||||
</IncomingShareProvider>
|
||||
<ConfirmDialogHost />
|
||||
</BlurTargetView>
|
||||
{/* Anchored-menu overlays render here — in-window, so the
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
createNativeStackScreen,
|
||||
type NativeStackNavigationOptions,
|
||||
} from "@react-navigation/native-stack";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "react-native";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
@@ -44,9 +45,20 @@ import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppea
|
||||
import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsClientStorageRouteScreen";
|
||||
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
|
||||
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
|
||||
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
|
||||
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
|
||||
import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen";
|
||||
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
|
||||
import {
|
||||
SettingsLegalDocumentCloseHeaderButton,
|
||||
SettingsLegalDocumentExternalHeaderButton,
|
||||
} from "./features/settings/components/SettingsLegalDocumentRouteScreen";
|
||||
import { useAppShortcuts } from "./features/shortcuts/useAppShortcuts";
|
||||
import { useIncomingShare } from "./features/sharing/IncomingShareProvider";
|
||||
import {
|
||||
EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
|
||||
transitionIncomingSharePresentation,
|
||||
} from "./features/sharing/incoming-share-presentation";
|
||||
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
|
||||
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
|
||||
|
||||
@@ -106,6 +118,14 @@ const SHEET_SOLID_HEADER_OPTIONS: AppScreenOptions = {
|
||||
unstable_navigationItemStyle: undefined,
|
||||
};
|
||||
|
||||
const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
|
||||
...SHEET_SOLID_HEADER_OPTIONS,
|
||||
headerBackVisible: false,
|
||||
headerLeft: SettingsLegalDocumentCloseHeaderButton,
|
||||
headerRight: () => <SettingsLegalDocumentExternalHeaderButton />,
|
||||
presentation: "fullScreenModal",
|
||||
};
|
||||
|
||||
const SettingsSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "Settings",
|
||||
screenOptions: {
|
||||
@@ -239,6 +259,7 @@ const WORKSPACE_OVERLAY_ROUTES = new Set([
|
||||
"GitConfirm",
|
||||
"GitOverview",
|
||||
"NewTaskSheet",
|
||||
"SettingsLegal",
|
||||
"SettingsSheet",
|
||||
"ThreadReviewComment",
|
||||
]);
|
||||
@@ -261,12 +282,30 @@ function RootStackLayout(props: {
|
||||
readonly children: React.ReactNode;
|
||||
readonly state: NavigationState;
|
||||
}) {
|
||||
const navigation = useNavigation();
|
||||
const { pendingShare } = useIncomingShare();
|
||||
const sharePresentationRef = useRef(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
|
||||
useAgentNotificationNavigation();
|
||||
useThreadOutboxDrain();
|
||||
// Presents the T3 Connect onboarding sheet after an in-session sign-in.
|
||||
useConnectOnboardingNavigation();
|
||||
// Launcher app shortcuts: routes shortcut taps and tracks opened threads.
|
||||
useAppShortcuts(props.state);
|
||||
useEffect(() => {
|
||||
const topRouteName = props.state.routes[props.state.index]?.name;
|
||||
const transition = transitionIncomingSharePresentation(sharePresentationRef.current, {
|
||||
isShareSheetPresented: topRouteName === "NewTaskSheet",
|
||||
pendingShareId: pendingShare?.id ?? null,
|
||||
});
|
||||
sharePresentationRef.current = transition.state;
|
||||
if (!transition.shareIdToPresent) {
|
||||
return;
|
||||
}
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTask",
|
||||
params: { incomingShareId: transition.shareIdToPresent },
|
||||
});
|
||||
}, [navigation, pendingShare, props.state]);
|
||||
// Full pathname (sheets included) for keyboard-command scoping; the
|
||||
// workspace layout only reacts to the underlying non-overlay route.
|
||||
const path = getPathFromState(props.state, navigationPathConfig);
|
||||
@@ -275,6 +314,7 @@ function RootStackLayout(props: {
|
||||
|
||||
return (
|
||||
<HardwareKeyboardCommandProvider pathname={pathname}>
|
||||
<ShowcaseCaptureCoordinator pathname={pathname} />
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
@@ -436,13 +476,21 @@ export const RootStack = createNativeStackNavigator({
|
||||
}),
|
||||
},
|
||||
}),
|
||||
SettingsLegal: createNativeStackScreen({
|
||||
screen: SettingsLegalRouteScreen,
|
||||
linking: "settings/legal",
|
||||
options: {
|
||||
...LEGAL_DOCUMENT_HEADER_OPTIONS,
|
||||
title: "Legal",
|
||||
},
|
||||
}),
|
||||
ConnectOnboarding: createNativeStackScreen({
|
||||
screen: ConnectOnboardingRouteScreen,
|
||||
linking: "connect-onboarding",
|
||||
options: {
|
||||
// Root screenOptions hide headers; formSheets that want the native
|
||||
// title bar opt back in with the sheet header preset.
|
||||
...SHEET_SOLID_HEADER_OPTIONS,
|
||||
// A root-level Android formSheet does not host the native stack bar;
|
||||
// the route renders an embedded AndroidSheetHeader instead.
|
||||
...(Platform.OS === "android" ? { headerShown: false } : SHEET_SOLID_HEADER_OPTIONS),
|
||||
title: "Set up T3 Connect",
|
||||
gestureEnabled: true,
|
||||
presentation: "formSheet",
|
||||
|
||||
@@ -51,6 +51,7 @@ export function AndroidScreenHeader(props: {
|
||||
readonly actions?: ReadonlyArray<AndroidHeaderAction>;
|
||||
readonly trailing?: ReactNode;
|
||||
readonly onBack?: () => void;
|
||||
readonly embedded?: boolean;
|
||||
}) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const foregroundColor = useThemeColor("--color-foreground");
|
||||
@@ -59,7 +60,7 @@ export function AndroidScreenHeader(props: {
|
||||
<View
|
||||
className="border-b border-header-border bg-header px-3 pb-2.5"
|
||||
style={{
|
||||
paddingTop: Math.max(insets.top, 12),
|
||||
paddingTop: props.embedded ? 8 : Math.max(insets.top, 12),
|
||||
}}
|
||||
>
|
||||
<View className="min-h-12 flex-row items-center gap-2">
|
||||
@@ -108,3 +109,9 @@ export function AndroidScreenHeader(props: {
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function AndroidSheetHeader(
|
||||
props: Omit<Parameters<typeof AndroidScreenHeader>[0], "embedded">,
|
||||
) {
|
||||
return <AndroidScreenHeader {...props} embedded />;
|
||||
}
|
||||
@@ -2,10 +2,11 @@ import { NativeHeaderToolbar } from "../../native/StackHeader";
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Pressable, RefreshControl, ScrollView, View } from "react-native";
|
||||
import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { reportAtomCommandResult, settlePromise } from "@t3tools/client-runtime/state/runtime";
|
||||
import { AndroidSheetHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
|
||||
@@ -81,9 +82,16 @@ function ConfiguredConnectOnboardingRouteScreen() {
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
<NativeHeaderToolbar placement="right">
|
||||
<NativeHeaderToolbar.Button icon="xmark" onPress={handleClose} separateBackground />
|
||||
</NativeHeaderToolbar>
|
||||
{Platform.OS === "android" ? (
|
||||
<AndroidSheetHeader
|
||||
title="Set up T3 Connect"
|
||||
actions={[{ accessibilityLabel: "Close", icon: "xmark", onPress: handleClose }]}
|
||||
/>
|
||||
) : (
|
||||
<NativeHeaderToolbar placement="right">
|
||||
<NativeHeaderToolbar.Button icon="xmark" onPress={handleClose} separateBackground />
|
||||
</NativeHeaderToolbar>
|
||||
)}
|
||||
<ScrollView
|
||||
alwaysBounceVertical
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
|
||||
@@ -33,6 +33,8 @@ import { type RelayEnvironmentView, useConnectionController } from "./useConnect
|
||||
export function CloudEnvironmentRows(props: {
|
||||
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
|
||||
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
|
||||
readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
|
||||
readonly showcaseSignedIn?: boolean;
|
||||
/**
|
||||
* Hide the "T3 Connect" section title + refresh button for hosts that
|
||||
* provide their own chrome (the onboarding sheet's native header and
|
||||
@@ -43,7 +45,8 @@ export function CloudEnvironmentRows(props: {
|
||||
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const controller = useConnectionController();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const availableCloudEnvironments = controller.availableRelayEnvironments;
|
||||
const availableCloudEnvironments =
|
||||
props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments;
|
||||
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
|
||||
const hasCloudRows =
|
||||
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
|
||||
@@ -64,7 +67,7 @@ export function CloudEnvironmentRows(props: {
|
||||
|
||||
const showHeader = props.showHeader ?? true;
|
||||
|
||||
if (!isSignedIn) return null;
|
||||
if (!(props.showcaseSignedIn ?? isSignedIn)) return null;
|
||||
|
||||
return (
|
||||
<View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { NativeReviewDiffRow } from "./nativeReviewDiffSurface";
|
||||
import type { NativeReviewDiffFile } from "./nativeReviewDiffTypes";
|
||||
import { highlightNativeReviewDiffVisibleRows } from "./nativeReviewDiffHighlighter";
|
||||
|
||||
const TYPESCRIPT_FILE: NativeReviewDiffFile = {
|
||||
id: "file-1",
|
||||
path: "example.ts",
|
||||
language: "typescript",
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
};
|
||||
|
||||
function makeLine(
|
||||
input: Pick<NativeReviewDiffRow, "id" | "content" | "change" | "oldLineNumber" | "newLineNumber">,
|
||||
): NativeReviewDiffRow {
|
||||
return {
|
||||
kind: "line",
|
||||
fileId: TYPESCRIPT_FILE.id,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function makeHunk(id: string): NativeReviewDiffRow {
|
||||
return {
|
||||
kind: "hunk",
|
||||
id,
|
||||
fileId: TYPESCRIPT_FILE.id,
|
||||
text: "@@",
|
||||
};
|
||||
}
|
||||
|
||||
function highlight(
|
||||
rows: ReadonlyArray<NativeReviewDiffRow>,
|
||||
alreadyHighlightedRowIds?: ReadonlySet<string>,
|
||||
) {
|
||||
return highlightNativeReviewDiffVisibleRows({
|
||||
rows,
|
||||
files: [TYPESCRIPT_FILE],
|
||||
scheme: "dark",
|
||||
engine: "javascript",
|
||||
firstRowIndex: 0,
|
||||
lastRowIndex: rows.length - 1,
|
||||
overscanRows: 0,
|
||||
maxRows: 100,
|
||||
alreadyHighlightedRowIds,
|
||||
});
|
||||
}
|
||||
|
||||
describe("highlightNativeReviewDiffVisibleRows", () => {
|
||||
it("does not carry grammar state across hunk boundaries", async () => {
|
||||
const exportRow = makeLine({
|
||||
id: "export-row",
|
||||
content: "export async function run() {}",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 100,
|
||||
});
|
||||
const rows = [
|
||||
makeHunk("hunk-1"),
|
||||
makeLine({
|
||||
id: "import-open",
|
||||
content: "import {",
|
||||
change: "context",
|
||||
oldLineNumber: 1,
|
||||
newLineNumber: 1,
|
||||
}),
|
||||
makeLine({
|
||||
id: "import-entry",
|
||||
content: " Model,",
|
||||
change: "context",
|
||||
oldLineNumber: 2,
|
||||
newLineNumber: 2,
|
||||
}),
|
||||
makeHunk("hunk-2"),
|
||||
exportRow,
|
||||
];
|
||||
|
||||
const [highlighted, standalone] = await Promise.all([
|
||||
highlight(rows),
|
||||
highlight([makeHunk("standalone-hunk"), exportRow]),
|
||||
]);
|
||||
|
||||
expect(highlighted.tokensByRowId[exportRow.id]).toEqual(standalone.tokensByRowId[exportRow.id]);
|
||||
});
|
||||
|
||||
it("keeps grammar state across inline comment rows", async () => {
|
||||
const openingRow = makeLine({
|
||||
id: "template-open",
|
||||
content: "const message = `open",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 1,
|
||||
});
|
||||
const closingRow = makeLine({
|
||||
id: "template-close",
|
||||
content: "closed`;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 2,
|
||||
});
|
||||
const trailingRow = makeLine({
|
||||
id: "trailing-row",
|
||||
content: "export const answer = 42;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 3,
|
||||
});
|
||||
const commentRow: NativeReviewDiffRow = {
|
||||
kind: "comment",
|
||||
id: "comment-1",
|
||||
fileId: TYPESCRIPT_FILE.id,
|
||||
commentText: "Review note",
|
||||
};
|
||||
|
||||
const [withComment, contiguous] = await Promise.all([
|
||||
highlight([openingRow, commentRow, closingRow, trailingRow]),
|
||||
highlight([openingRow, closingRow, trailingRow]),
|
||||
]);
|
||||
|
||||
expect(withComment.tokensByRowId).toEqual(contiguous.tokensByRowId);
|
||||
});
|
||||
|
||||
it("does not join unhighlighted rows across cached gaps", async () => {
|
||||
const trailingRow = makeLine({
|
||||
id: "trailing-row",
|
||||
content: "export const answer = 42;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 3,
|
||||
});
|
||||
const rows = [
|
||||
makeLine({
|
||||
id: "template-open",
|
||||
content: "const message = `open",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 1,
|
||||
}),
|
||||
makeLine({
|
||||
id: "template-close",
|
||||
content: "closed`;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 2,
|
||||
}),
|
||||
trailingRow,
|
||||
];
|
||||
|
||||
const [highlighted, standalone] = await Promise.all([
|
||||
highlight(rows, new Set(["template-close"])),
|
||||
highlight([trailingRow]),
|
||||
]);
|
||||
|
||||
expect(highlighted.tokensByRowId[trailingRow.id]).toEqual(
|
||||
standalone.tokensByRowId[trailingRow.id],
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps deletion grammar state out of addition rows", async () => {
|
||||
const additionRow = makeLine({
|
||||
id: "addition-row",
|
||||
content: "export const answer = 42;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 1,
|
||||
});
|
||||
const rows = [
|
||||
makeLine({
|
||||
id: "deletion-row",
|
||||
content: "const removed = `open",
|
||||
change: "delete",
|
||||
oldLineNumber: 1,
|
||||
newLineNumber: null,
|
||||
}),
|
||||
additionRow,
|
||||
];
|
||||
|
||||
const [highlighted, standalone] = await Promise.all([
|
||||
highlight(rows),
|
||||
highlight([additionRow]),
|
||||
]);
|
||||
|
||||
expect(highlighted.tokensByRowId[additionRow.id]).toEqual(
|
||||
standalone.tokensByRowId[additionRow.id],
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -56,6 +56,11 @@ interface NativeReviewDiffLineRow extends NativeReviewDiffRow {
|
||||
readonly content: string;
|
||||
}
|
||||
|
||||
interface IndexedNativeReviewDiffLineRow {
|
||||
readonly row: NativeReviewDiffLineRow;
|
||||
readonly rowIndex: number;
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffTokenChunk {
|
||||
readonly chunkIndex: number;
|
||||
readonly fileId: string;
|
||||
@@ -308,6 +313,58 @@ function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDi
|
||||
return row.kind === "line" && typeof row.fileId === "string" && typeof row.content === "string";
|
||||
}
|
||||
|
||||
function hasConsecutiveLineNumbers(
|
||||
previous: number | null | undefined,
|
||||
next: number | null | undefined,
|
||||
): boolean {
|
||||
return typeof previous === "number" && typeof next === "number" && next === previous + 1;
|
||||
}
|
||||
|
||||
function hasOnlyCommentRowsBetween(
|
||||
rows: ReadonlyArray<NativeReviewDiffRow>,
|
||||
previousRowIndex: number,
|
||||
nextRowIndex: number,
|
||||
): boolean {
|
||||
for (let rowIndex = previousRowIndex + 1; rowIndex < nextRowIndex; rowIndex += 1) {
|
||||
if (rows[rowIndex]?.kind !== "comment") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function canShareGrammarContext(
|
||||
previous: IndexedNativeReviewDiffLineRow,
|
||||
next: IndexedNativeReviewDiffLineRow,
|
||||
rows: ReadonlyArray<NativeReviewDiffRow>,
|
||||
): boolean {
|
||||
if (
|
||||
next.row.fileId !== previous.row.fileId ||
|
||||
!hasOnlyCommentRowsBetween(rows, previous.rowIndex, next.rowIndex)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (previous.row.change === "delete" || next.row.change === "delete") {
|
||||
return (
|
||||
previous.row.change !== "add" &&
|
||||
next.row.change !== "add" &&
|
||||
hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber)
|
||||
);
|
||||
}
|
||||
|
||||
if (previous.row.change === "add" || next.row.change === "add") {
|
||||
return hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber);
|
||||
}
|
||||
|
||||
return (
|
||||
previous.row.change === "context" &&
|
||||
next.row.change === "context" &&
|
||||
hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber) &&
|
||||
hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber)
|
||||
);
|
||||
}
|
||||
|
||||
function groupLineRowsByFileId(rows: ReadonlyArray<NativeReviewDiffRow>) {
|
||||
const rowsByFileId = new Map<string, NativeReviewDiffLineRow[]>();
|
||||
for (const row of rows) {
|
||||
@@ -360,7 +417,7 @@ export async function highlightNativeReviewDiffVisibleRows(
|
||||
const maxRows = input.maxRows ?? NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS;
|
||||
const startIndex = clampRowIndex(input.firstRowIndex - overscanRows, input.rows);
|
||||
const endIndex = clampRowIndex(input.lastRowIndex + overscanRows, input.rows);
|
||||
const selectedRows: NativeReviewDiffLineRow[] = [];
|
||||
const selectedRows: IndexedNativeReviewDiffLineRow[] = [];
|
||||
|
||||
for (
|
||||
let rowIndex = startIndex;
|
||||
@@ -374,12 +431,12 @@ export async function highlightNativeReviewDiffVisibleRows(
|
||||
!input.alreadyHighlightedRowIds?.has(row.id) &&
|
||||
fileMap.has(row.fileId)
|
||||
) {
|
||||
selectedRows.push(row);
|
||||
selectedRows.push({ row, rowIndex });
|
||||
}
|
||||
}
|
||||
|
||||
const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
|
||||
let segmentRows: NativeReviewDiffLineRow[] = [];
|
||||
let segmentRows: IndexedNativeReviewDiffLineRow[] = [];
|
||||
let segmentFile: NativeReviewDiffFile | undefined;
|
||||
|
||||
const flushSegment = () => {
|
||||
@@ -389,27 +446,34 @@ export async function highlightNativeReviewDiffVisibleRows(
|
||||
return;
|
||||
}
|
||||
|
||||
const code = segmentRows.map((row) => row.content).join("\n");
|
||||
const code = segmentRows.map(({ row }) => row.content).join("\n");
|
||||
const tokenLines = highlighter.tokenize(code, { lang: segmentFile.language, theme });
|
||||
segmentRows.forEach((row, rowIndex) => {
|
||||
segmentRows.forEach(({ row }, rowIndex) => {
|
||||
tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
|
||||
});
|
||||
segmentRows = [];
|
||||
segmentFile = undefined;
|
||||
};
|
||||
|
||||
for (const row of selectedRows) {
|
||||
for (const selectedRow of selectedRows) {
|
||||
const { row } = selectedRow;
|
||||
const file = fileMap.get(row.fileId);
|
||||
if (!file) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (segmentFile && segmentFile.id !== file.id) {
|
||||
const previousRow = segmentRows.at(-1);
|
||||
if (
|
||||
segmentFile &&
|
||||
(segmentFile.id !== file.id ||
|
||||
(previousRow !== undefined &&
|
||||
!canShareGrammarContext(previousRow, selectedRow, input.rows)))
|
||||
) {
|
||||
flushSegment();
|
||||
}
|
||||
|
||||
segmentFile = file;
|
||||
segmentRows.push(row);
|
||||
segmentRows.push(selectedRow);
|
||||
}
|
||||
flushSegment();
|
||||
|
||||
|
||||
@@ -96,5 +96,22 @@ describe("isPendingNativeViewRegistration", () => {
|
||||
new Error("Unable to find the 'T3ReviewDiffView' view for this native tag"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPendingNativeViewRegistration(
|
||||
new Error(
|
||||
"Unable to find the class expo.modules.t3reviewdiff.T3ReviewDiffView view with tag 1150",
|
||||
),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isNativeReviewDiffDrawEvent", () => {
|
||||
it("accepts only native events emitted after diff rows draw", async () => {
|
||||
const { isNativeReviewDiffDrawEvent } = await import("./nativeReviewDiffSurface");
|
||||
|
||||
expect(isNativeReviewDiffDrawEvent({ message: "draw-metrics" })).toBe(true);
|
||||
expect(isNativeReviewDiffDrawEvent({ message: "visible-range" })).toBe(true);
|
||||
expect(isNativeReviewDiffDrawEvent({ message: "rows-decoded" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -149,6 +149,10 @@ export interface NativeReviewDiffViewHandle {
|
||||
readonly scrollToTop: (animated?: boolean) => Promise<void>;
|
||||
}
|
||||
|
||||
export function isNativeReviewDiffDrawEvent(payload: Readonly<Record<string, unknown>>): boolean {
|
||||
return payload.message === "draw-metrics" || payload.message === "visible-range";
|
||||
}
|
||||
|
||||
interface NativeReviewDiffViewRef {
|
||||
readonly setRowsJson: (rowsJson: string) => Promise<void>;
|
||||
readonly setTokensJson: (tokensJson: string) => Promise<void>;
|
||||
@@ -170,9 +174,11 @@ let nativeReviewDiffViewResolutionFailed = false;
|
||||
type NativeReviewDiffPayloadMethod = "setRowsJson" | "setTokensJson" | "setTokensPatchJson";
|
||||
|
||||
export function isPendingNativeViewRegistration(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) return false;
|
||||
return (
|
||||
error instanceof Error &&
|
||||
error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`)
|
||||
error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`) ||
|
||||
(error.message.includes("Unable to find the class") &&
|
||||
error.message.includes("T3ReviewDiffView view with tag"))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -167,7 +167,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const listRef = useRef<LegendListRef | null>(null);
|
||||
const insets = useSafeAreaInsets();
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
|
||||
const effectiveGroupDisplayStates = useMemo(() => {
|
||||
const next = new Map(groupDisplayStates);
|
||||
if (!AsyncResult.isSuccess(preferencesResult)) {
|
||||
|
||||
@@ -56,6 +56,7 @@ import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
import { ThreadGitMenu } from "../threads/ThreadGitControls";
|
||||
import { useReviewCacheForThread } from "./reviewState";
|
||||
import {
|
||||
isNativeReviewDiffDrawEvent,
|
||||
type NativeReviewDiffViewHandle,
|
||||
resolveNativeReviewDiffView,
|
||||
} from "../diffs/nativeReviewDiffSurface";
|
||||
@@ -71,8 +72,10 @@ import { resolveReviewAvailability } from "./reviewAvailability";
|
||||
import { resolveSelectedReviewFileId } from "./reviewPaneSelection";
|
||||
import { buildReviewSectionMenu } from "./review-section-menu";
|
||||
import type { ReviewSectionItem } from "./reviewModel";
|
||||
import { markNativeShowcaseReady } from "../showcase/nativeShowcaseScene";
|
||||
|
||||
const REVIEW_HEADER_SPACING = 0;
|
||||
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
|
||||
|
||||
const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {
|
||||
return (
|
||||
@@ -394,6 +397,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
|
||||
});
|
||||
const NativeReviewDiffView = resolveNativeReviewDiffView()!;
|
||||
const nativeReviewDiffViewRef = useRef<NativeReviewDiffViewHandle>(null);
|
||||
const showcasedReviewDrawRef = useRef<string | null>(null);
|
||||
// Native pull-to-refresh on the diff surface (replaces the old Refresh menu item).
|
||||
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
|
||||
const handlePullToRefresh = useCallback(async () => {
|
||||
@@ -435,6 +439,25 @@ export function ReviewSheet(props: ReviewSheetProps) {
|
||||
selectedRowIds: commentSelection.selectedRowIds,
|
||||
canHighlight: parsedDiff.kind === "files",
|
||||
});
|
||||
const showcaseReviewKey =
|
||||
SHOWCASE_ENABLED && parsedDiff.kind === "files" && selectedSection
|
||||
? `${reviewCache.threadKey}:${selectedSection.id}:${nativeBridge.tokensResetKey}`
|
||||
: null;
|
||||
const handleNativeDebug = useCallback(
|
||||
(event: NativeSyntheticEvent<Record<string, unknown>>) => {
|
||||
nativeBridge.onDebug(event);
|
||||
if (
|
||||
showcaseReviewKey === null ||
|
||||
showcasedReviewDrawRef.current === showcaseReviewKey ||
|
||||
!isNativeReviewDiffDrawEvent(event.nativeEvent)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
showcasedReviewDrawRef.current = showcaseReviewKey;
|
||||
markNativeShowcaseReady("review");
|
||||
},
|
||||
[nativeBridge.onDebug, showcaseReviewKey],
|
||||
);
|
||||
|
||||
const handleSelectFile = useCallback(
|
||||
(fileId: string | null) => {
|
||||
@@ -788,7 +811,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
|
||||
tokensPatchJson={nativeBridge.tokensPatchJson}
|
||||
tokensResetKey={nativeBridge.tokensResetKey}
|
||||
viewedFileIdsJson={nativeBridge.viewedFileIdsJson}
|
||||
onDebug={nativeBridge.onDebug}
|
||||
onDebug={handleNativeDebug}
|
||||
onPressLine={commentSelection.onPressLine}
|
||||
onVisibleFileChange={handleVisibleFileChange}
|
||||
onToggleComment={nativeBridge.onToggleComment}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/Stac
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useState } from "react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Platform, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
@@ -15,6 +15,15 @@ import { splitEnvironmentSections } from "../connection/environmentSections";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import {
|
||||
applyShowcaseLocalEnvironmentDisplayUrls,
|
||||
resolveShowcaseEnvironmentUpdateDisplayUrl,
|
||||
SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,
|
||||
SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS,
|
||||
} from "../showcase/showcaseEnvironmentRows";
|
||||
import { markNativeShowcaseReady } from "../showcase/nativeShowcaseScene";
|
||||
|
||||
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
|
||||
|
||||
export function SettingsEnvironmentsRouteScreen() {
|
||||
const {
|
||||
@@ -25,18 +34,56 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
} = useRemoteConnections();
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const { localEnvironments, connectedCloudEnvironments } = splitEnvironmentSections({
|
||||
const environmentSections = splitEnvironmentSections({
|
||||
connectedEnvironments,
|
||||
cloudEnvironments: null,
|
||||
});
|
||||
const localEnvironments = SHOWCASE_ENABLED
|
||||
? applyShowcaseLocalEnvironmentDisplayUrls(environmentSections.localEnvironments)
|
||||
: environmentSections.localEnvironments;
|
||||
const connectedCloudEnvironments = SHOWCASE_ENABLED
|
||||
? SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS
|
||||
: environmentSections.connectedCloudEnvironments;
|
||||
const hasLocalEnvironments = localEnvironments.length > 0;
|
||||
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
const headerIconColor = useThemeColor("--color-icon");
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED) return;
|
||||
const timer = setTimeout(() => markNativeShowcaseReady("environments"), 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
const handleToggle = useCallback((environmentId: EnvironmentId) => {
|
||||
setExpandedId((prev) => (prev === environmentId ? null : environmentId));
|
||||
}, []);
|
||||
const handleUpdateEnvironment = useCallback(
|
||||
(
|
||||
environmentId: EnvironmentId,
|
||||
updates: { readonly label: string; readonly displayUrl: string },
|
||||
) => {
|
||||
if (!SHOWCASE_ENABLED) return onUpdateEnvironment(environmentId, updates);
|
||||
const actualEnvironment = environmentSections.localEnvironments.find(
|
||||
(environment) => environment.environmentId === environmentId,
|
||||
);
|
||||
const presentedEnvironment = localEnvironments.find(
|
||||
(environment) => environment.environmentId === environmentId,
|
||||
);
|
||||
return onUpdateEnvironment(environmentId, {
|
||||
...updates,
|
||||
displayUrl:
|
||||
actualEnvironment && presentedEnvironment
|
||||
? resolveShowcaseEnvironmentUpdateDisplayUrl({
|
||||
actualDisplayUrl: actualEnvironment.displayUrl,
|
||||
presentedDisplayUrl: presentedEnvironment.displayUrl,
|
||||
submittedDisplayUrl: updates.displayUrl,
|
||||
})
|
||||
: updates.displayUrl,
|
||||
});
|
||||
},
|
||||
[environmentSections.localEnvironments, localEnvironments, onUpdateEnvironment],
|
||||
);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
@@ -92,7 +139,7 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
onToggle={() => handleToggle(environment.environmentId)}
|
||||
onReconnect={onReconnectEnvironment}
|
||||
onRemove={onRemoveEnvironmentPress}
|
||||
onUpdate={onUpdateEnvironment}
|
||||
onUpdate={handleUpdateEnvironment}
|
||||
/>
|
||||
</View>
|
||||
))}
|
||||
@@ -114,10 +161,16 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
</View>
|
||||
)}
|
||||
|
||||
{hasCloudPublicConfig() ? (
|
||||
{hasCloudPublicConfig() || SHOWCASE_ENABLED ? (
|
||||
<CloudEnvironmentRows
|
||||
connectedCloudEnvironments={connectedCloudEnvironments}
|
||||
onReconnectEnvironment={onReconnectEnvironment}
|
||||
{...(SHOWCASE_ENABLED
|
||||
? {
|
||||
showcaseAvailableEnvironments: SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,
|
||||
showcaseSignedIn: true,
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { SettingsLegalDocumentRouteScreen } from "./components/SettingsLegalDocumentRouteScreen";
|
||||
import { LEGAL_URL } from "./lib/legal-document-url";
|
||||
|
||||
export function SettingsLegalRouteScreen() {
|
||||
return <SettingsLegalDocumentRouteScreen documentName="Legal" documentUrl={LEGAL_URL} />;
|
||||
}
|
||||
@@ -537,6 +537,7 @@ function AppSettingsSection() {
|
||||
return (
|
||||
<SettingsSection title="App">
|
||||
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
|
||||
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
|
||||
<View className="flex-row items-center gap-4 p-4">
|
||||
<SymbolView
|
||||
name="info.circle"
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { type NavigationProp, type ParamListBase, useNavigation } from "@react-navigation/native";
|
||||
import { useCallback, useLayoutEffect, useState } from "react";
|
||||
import { ActivityIndicator, Linking, Pressable, View } from "react-native";
|
||||
import { WebView } from "react-native-webview";
|
||||
|
||||
import { AppText as Text } from "../../../components/AppText";
|
||||
import { LoadingStrip } from "../../../components/LoadingStrip";
|
||||
import { SymbolView } from "../../../components/AppSymbol";
|
||||
import { useThemeColor } from "../../../lib/useThemeColor";
|
||||
import { isLegalDocumentUrl, LEGAL_URL } from "../lib/legal-document-url";
|
||||
|
||||
export function SettingsLegalDocumentCloseHeaderButton() {
|
||||
const navigation = useNavigation();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel="Close legal document"
|
||||
accessibilityRole="button"
|
||||
hitSlop={12}
|
||||
onPress={() => navigation.goBack()}
|
||||
className="p-2 active:opacity-60"
|
||||
>
|
||||
<SymbolView
|
||||
name="xmark"
|
||||
size={18}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsLegalDocumentExternalHeaderButton({
|
||||
externalUrl = LEGAL_URL,
|
||||
}: {
|
||||
readonly externalUrl?: string;
|
||||
}) {
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const safeExternalUrl = isLegalDocumentUrl(externalUrl) ? externalUrl : LEGAL_URL;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel="Open legal documents in external browser"
|
||||
accessibilityRole="button"
|
||||
hitSlop={12}
|
||||
onPress={() => void Linking.openURL(safeExternalUrl).catch(() => undefined)}
|
||||
className="p-2 active:opacity-60"
|
||||
>
|
||||
<SymbolView
|
||||
name="safari"
|
||||
size={19}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
weight="regular"
|
||||
/>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
interface SettingsLegalDocumentRouteScreenProps {
|
||||
readonly documentName: string;
|
||||
readonly documentUrl: string;
|
||||
}
|
||||
|
||||
export function SettingsLegalDocumentRouteScreen({
|
||||
documentName,
|
||||
documentUrl,
|
||||
}: SettingsLegalDocumentRouteScreenProps) {
|
||||
const navigation = useNavigation<NavigationProp<ParamListBase>>();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [loadProgress, setLoadProgress] = useState(0);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [externalUrl, setExternalUrl] = useState(documentUrl);
|
||||
const renderExternalHeaderButton = useCallback(
|
||||
() => <SettingsLegalDocumentExternalHeaderButton externalUrl={externalUrl} />,
|
||||
[externalUrl],
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
navigation.setOptions({
|
||||
headerRight: renderExternalHeaderButton,
|
||||
});
|
||||
}, [navigation, renderExternalHeaderButton]);
|
||||
|
||||
const openExternalUrl = useCallback((url: string) => {
|
||||
void Linking.openURL(url).catch(() => undefined);
|
||||
}, []);
|
||||
if (loadError) {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center gap-4 bg-sheet px-8">
|
||||
<SymbolView
|
||||
name="exclamationmark.triangle"
|
||||
size={32}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
weight="regular"
|
||||
/>
|
||||
<View className="items-center gap-2">
|
||||
<Text className="text-center font-t3-bold text-lg text-foreground">
|
||||
Couldn't load the {documentName.toLowerCase()}
|
||||
</Text>
|
||||
<Text selectable className="text-center text-sm leading-normal text-foreground-muted">
|
||||
{loadError}
|
||||
</Text>
|
||||
</View>
|
||||
<View className="w-full max-w-[320px] gap-2">
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={() => {
|
||||
setLoadError(null);
|
||||
setReloadKey((value) => value + 1);
|
||||
}}
|
||||
className="items-center rounded-xl bg-foreground px-4 py-3 active:opacity-80"
|
||||
>
|
||||
<Text className="font-t3-bold text-base text-sheet">Try Again</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="link"
|
||||
onPress={() => openExternalUrl(documentUrl)}
|
||||
className="items-center rounded-xl px-4 py-3 active:bg-foreground/5"
|
||||
>
|
||||
<Text className="font-t3-medium text-base text-foreground-muted">Open in Browser</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="relative flex-1 bg-sheet">
|
||||
{loadProgress > 0 && loadProgress < 1 ? <LoadingStrip progress={loadProgress} /> : null}
|
||||
<WebView
|
||||
key={reloadKey}
|
||||
source={{ uri: documentUrl }}
|
||||
originWhitelist={["http://*", "https://*", "mailto:*"]}
|
||||
cacheEnabled={false}
|
||||
cacheMode="LOAD_NO_CACHE"
|
||||
allowsBackForwardNavigationGestures
|
||||
domStorageEnabled={false}
|
||||
incognito
|
||||
javaScriptEnabled={false}
|
||||
setSupportMultipleWindows={false}
|
||||
sharedCookiesEnabled={false}
|
||||
thirdPartyCookiesEnabled={false}
|
||||
startInLoadingState
|
||||
onShouldStartLoadWithRequest={(request) => {
|
||||
if (isLegalDocumentUrl(request.url)) return true;
|
||||
|
||||
openExternalUrl(request.url);
|
||||
return false;
|
||||
}}
|
||||
onLoadProgress={(event) => {
|
||||
setLoadProgress(event.nativeEvent.progress);
|
||||
}}
|
||||
onLoadStart={() => {
|
||||
setLoadProgress(0.05);
|
||||
setLoadError(null);
|
||||
}}
|
||||
onLoadEnd={(event) => {
|
||||
if (isLegalDocumentUrl(event.nativeEvent.url)) {
|
||||
setExternalUrl(event.nativeEvent.url);
|
||||
}
|
||||
setLoadProgress(0);
|
||||
}}
|
||||
onError={(event) => {
|
||||
setLoadProgress(0);
|
||||
setLoadError(event.nativeEvent.description || "The page could not be loaded.");
|
||||
}}
|
||||
onHttpError={(event) => {
|
||||
if (!isLegalDocumentUrl(event.nativeEvent.url)) return;
|
||||
setLoadProgress(0);
|
||||
setLoadError(`The server returned status ${event.nativeEvent.statusCode}.`);
|
||||
}}
|
||||
renderLoading={() => (
|
||||
<View className="absolute inset-0 items-center justify-center bg-sheet">
|
||||
<ActivityIndicator />
|
||||
</View>
|
||||
)}
|
||||
style={{ flex: 1, backgroundColor: "transparent" }}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { SymbolView } from "../../../components/AppSymbol";
|
||||
|
||||
import { AppText as Text } from "../../../components/AppText";
|
||||
import { useThemeColor } from "../../../lib/useThemeColor";
|
||||
import type { SettingsSheetTarget } from "./settings-sheet-targets";
|
||||
import type { SettingsLegalDocumentTarget, SettingsSheetTarget } from "./settings-sheet-targets";
|
||||
|
||||
type SymbolName = ComponentProps<typeof SymbolView>["name"];
|
||||
|
||||
@@ -16,6 +16,7 @@ export function SettingsRow(props: {
|
||||
readonly label: string;
|
||||
readonly value?: string;
|
||||
readonly target?: SettingsSheetTarget;
|
||||
readonly fullScreenTarget?: SettingsLegalDocumentTarget;
|
||||
readonly onPress?: () => void;
|
||||
}) {
|
||||
const navigation = useNavigation();
|
||||
@@ -72,6 +73,20 @@ export function SettingsRow(props: {
|
||||
);
|
||||
}
|
||||
|
||||
const fullScreenTarget = props.fullScreenTarget;
|
||||
if (fullScreenTarget) {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel={props.label}
|
||||
accessibilityRole="button"
|
||||
disabled={props.disabled}
|
||||
onPress={() => navigation.navigate(fullScreenTarget)}
|
||||
>
|
||||
{content}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Pressable accessibilityRole="button" disabled={props.disabled} onPress={props.onPress}>
|
||||
{content}
|
||||
|
||||
@@ -3,3 +3,5 @@ export type SettingsSheetTarget =
|
||||
| "SettingsArchive"
|
||||
| "SettingsAppearance"
|
||||
| "SettingsClientStorage";
|
||||
|
||||
export type SettingsLegalDocumentTarget = "SettingsLegal";
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { isLegalDocumentUrl } from "./legal-document-url";
|
||||
|
||||
describe("isLegalDocumentUrl", () => {
|
||||
it.each([
|
||||
"https://t3.codes/legal",
|
||||
"https://t3.codes/legal/",
|
||||
"https://t3.codes/privacy-policy?source=app",
|
||||
"https://t3.codes/terms-of-service#updates",
|
||||
"https://t3.codes/security-policy",
|
||||
])("allows a configured legal document: %s", (url) => {
|
||||
expect(isLegalDocumentUrl(url)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"https://t3.codes/download",
|
||||
"https://example.com/legal",
|
||||
"javascript:alert(1)",
|
||||
"not-a-url",
|
||||
])("rejects a URL outside the legal-document allowlist: %s", (url) => {
|
||||
expect(isLegalDocumentUrl(url)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
const DEFAULT_MARKETING_SITE_URL = "https://t3.codes";
|
||||
|
||||
function resolveMarketingSiteUrl(override: string | undefined): URL {
|
||||
try {
|
||||
const url = new URL(override?.trim() || DEFAULT_MARKETING_SITE_URL);
|
||||
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
||||
return new URL(DEFAULT_MARKETING_SITE_URL);
|
||||
}
|
||||
|
||||
url.search = "";
|
||||
url.hash = "";
|
||||
url.pathname = `${url.pathname.replace(/\/+$/, "")}/`;
|
||||
return url;
|
||||
} catch {
|
||||
return new URL(DEFAULT_MARKETING_SITE_URL);
|
||||
}
|
||||
}
|
||||
|
||||
const MARKETING_SITE_URL = resolveMarketingSiteUrl(process.env.EXPO_PUBLIC_MARKETING_SITE_URL);
|
||||
|
||||
function marketingSiteDocumentUrl(path: string): string {
|
||||
return new URL(path, MARKETING_SITE_URL).toString();
|
||||
}
|
||||
|
||||
export const PRIVACY_POLICY_URL = marketingSiteDocumentUrl("privacy-policy");
|
||||
export const SECURITY_POLICY_URL = marketingSiteDocumentUrl("security-policy");
|
||||
export const TERMS_OF_SERVICE_URL = marketingSiteDocumentUrl("terms-of-service");
|
||||
export const LEGAL_URL = marketingSiteDocumentUrl("legal");
|
||||
|
||||
export const ALLOWED_LEGAL_DOCUMENT_URLS = [
|
||||
LEGAL_URL,
|
||||
PRIVACY_POLICY_URL,
|
||||
TERMS_OF_SERVICE_URL,
|
||||
SECURITY_POLICY_URL,
|
||||
] as const;
|
||||
|
||||
function webDocumentIdentity(value: string): string | null {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol !== "https:" && url.protocol !== "http:") return null;
|
||||
|
||||
const pathname = url.pathname.replace(/\/+$/, "") || "/";
|
||||
return `${url.origin}${pathname}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const ALLOWED_LEGAL_DOCUMENT_IDENTITIES = new Set(
|
||||
ALLOWED_LEGAL_DOCUMENT_URLS.map(webDocumentIdentity).filter(
|
||||
(value): value is string => value !== null,
|
||||
),
|
||||
);
|
||||
|
||||
export function isLegalDocumentUrl(value: string): boolean {
|
||||
const identity = webDocumentIdentity(value);
|
||||
return identity !== null && ALLOWED_LEGAL_DOCUMENT_IDENTITIES.has(identity);
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
import Constants from "expo-constants";
|
||||
import * as Crypto from "expo-crypto";
|
||||
import {
|
||||
clearSharedPayloads,
|
||||
getResolvedSharedPayloadsAsync,
|
||||
getSharedPayloads,
|
||||
type ResolvedSharePayload,
|
||||
type SharePayload,
|
||||
} from "expo-sharing";
|
||||
import React, { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
||||
import { Alert, AppState, Platform } from "react-native";
|
||||
|
||||
import {
|
||||
buildIncomingShareDraft,
|
||||
type IncomingShareDestination,
|
||||
type IncomingShareDraft,
|
||||
} from "./incoming-share-model";
|
||||
import { IncomingShareInbox } from "./incoming-share-inbox";
|
||||
import {
|
||||
loadIncomingShareDrafts,
|
||||
removeIncomingShareDraft,
|
||||
writeIncomingShareDraft,
|
||||
} from "./incoming-share-storage";
|
||||
|
||||
type IncomingShareContextValue = {
|
||||
readonly pendingShare: IncomingShareDraft | null;
|
||||
readonly isLoading: boolean;
|
||||
readonly error: Error | null;
|
||||
readonly getShare: (shareId: string) => IncomingShareDraft | null;
|
||||
readonly reserveShare: (shareId: string, destination: IncomingShareDestination) => Promise<void>;
|
||||
readonly releaseShareReservation: (
|
||||
shareId: string,
|
||||
expectedDestination: IncomingShareDestination,
|
||||
) => Promise<void>;
|
||||
readonly consumeShare: (shareId: string) => Promise<void>;
|
||||
readonly refresh: () => Promise<void>;
|
||||
};
|
||||
|
||||
const IncomingShareContext = React.createContext<IncomingShareContextValue | null>(null);
|
||||
|
||||
function receiveSharingEnabled(): boolean {
|
||||
if (Platform.OS === "android") {
|
||||
return true;
|
||||
}
|
||||
if (Platform.OS !== "ios") {
|
||||
return false;
|
||||
}
|
||||
return Constants.expoConfig?.extra?.iosPersonalTeamBuild !== true;
|
||||
}
|
||||
|
||||
async function resolvedPayloadsForImages(): Promise<ReadonlyArray<ResolvedSharePayload>> {
|
||||
try {
|
||||
return await getResolvedSharedPayloadsAsync();
|
||||
} catch (error) {
|
||||
// iOS already gives the containing app a copied file:// URL, so raw
|
||||
// payloads remain usable. Android normally resolves content:// into a
|
||||
// private cache file; its modern File API can still read the raw URI when
|
||||
// resolution fails.
|
||||
console.warn("[incoming-share] could not resolve shared file metadata", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function incomingShareIdForPayloads(payloads: ReadonlyArray<SharePayload>): Promise<string> {
|
||||
const fingerprint = JSON.stringify(
|
||||
payloads.map((payload) => ({
|
||||
shareType: payload.shareType,
|
||||
mimeType: payload.mimeType ?? null,
|
||||
value: payload.value,
|
||||
})),
|
||||
);
|
||||
const digest = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, fingerprint);
|
||||
return `share-${digest}`;
|
||||
}
|
||||
|
||||
async function readBase64(uri: string): Promise<string> {
|
||||
const { File } = await import("expo-file-system");
|
||||
return new File(uri).base64();
|
||||
}
|
||||
|
||||
async function removeOwnedFile(uri: string): Promise<void> {
|
||||
if (!uri.startsWith("file:")) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { File } = await import("expo-file-system");
|
||||
const file = new File(uri);
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("[incoming-share] could not remove temporary shared file", error);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeReplayedImagePayloadFiles(
|
||||
payloads: ReadonlyArray<SharePayload>,
|
||||
): Promise<void> {
|
||||
const uris = new Set<string>();
|
||||
for (const payload of payloads) {
|
||||
if (payload.shareType === "image") {
|
||||
uris.add(payload.value);
|
||||
}
|
||||
}
|
||||
if (uris.size === 0) {
|
||||
return;
|
||||
}
|
||||
const resolvedPayloads = await resolvedPayloadsForImages();
|
||||
for (const payload of resolvedPayloads) {
|
||||
if (payload.shareType === "image" && payload.contentUri) {
|
||||
uris.add(payload.contentUri);
|
||||
}
|
||||
}
|
||||
await Promise.all([...uris].map(removeOwnedFile));
|
||||
}
|
||||
|
||||
// Keep one operation queue across provider remounts (including development
|
||||
// Strict Mode remounts) so two app lifecycle notifications cannot ingest the
|
||||
// same native handoff independently.
|
||||
const incomingShareInbox = new IncomingShareInbox({
|
||||
loadDrafts: loadIncomingShareDrafts,
|
||||
writeDraft: writeIncomingShareDraft,
|
||||
removeDraft: removeIncomingShareDraft,
|
||||
getPayloads: getSharedPayloads,
|
||||
clearPayloads: clearSharedPayloads,
|
||||
buildDraft: async ({ payloads, id, createdAt }) => {
|
||||
const cleanupUris = new Set<string>();
|
||||
const resolvedPayloads = payloads.some((payload) => payload.shareType === "image")
|
||||
? await resolvedPayloadsForImages()
|
||||
: [];
|
||||
const draft = await buildIncomingShareDraft({
|
||||
payloads,
|
||||
resolvedPayloads,
|
||||
fileReader: {
|
||||
readBase64,
|
||||
removeOwnedFile: (uri) => {
|
||||
cleanupUris.add(uri);
|
||||
},
|
||||
},
|
||||
id,
|
||||
createdAt,
|
||||
});
|
||||
return {
|
||||
draft,
|
||||
cleanup: async () => {
|
||||
await Promise.all([...cleanupUris].map(removeOwnedFile));
|
||||
},
|
||||
};
|
||||
},
|
||||
cleanupReplayedPayloads: removeReplayedImagePayloadFiles,
|
||||
idForPayloads: incomingShareIdForPayloads,
|
||||
now: () => new Date().toISOString(),
|
||||
onClearError: (error) => {
|
||||
console.warn("[incoming-share] could not acknowledge native payload", error);
|
||||
},
|
||||
onCleanupError: (error) => {
|
||||
console.warn("[incoming-share] could not remove temporary shared file", error);
|
||||
},
|
||||
});
|
||||
|
||||
export function IncomingShareProvider(props: React.PropsWithChildren) {
|
||||
const enabled = receiveSharingEnabled();
|
||||
const [drafts, setDrafts] = useState<ReadonlyArray<IncomingShareDraft>>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
const refreshPromiseRef = useRef<Promise<void> | null>(null);
|
||||
const mountedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (refreshPromiseRef.current) {
|
||||
return refreshPromiseRef.current;
|
||||
}
|
||||
|
||||
const operation = (async () => {
|
||||
try {
|
||||
const snapshot = await incomingShareInbox.refresh({ ingestNative: enabled });
|
||||
if (mountedRef.current) {
|
||||
setDrafts(snapshot);
|
||||
setError(null);
|
||||
}
|
||||
} catch (cause) {
|
||||
const persisted = await incomingShareInbox
|
||||
.refresh({ ingestNative: false })
|
||||
.catch(() => null);
|
||||
if (mountedRef.current) {
|
||||
if (persisted) {
|
||||
setDrafts(persisted);
|
||||
}
|
||||
setError(cause instanceof Error ? cause : new Error("Could not import shared content."));
|
||||
}
|
||||
}
|
||||
})().finally(() => {
|
||||
refreshPromiseRef.current = null;
|
||||
});
|
||||
|
||||
refreshPromiseRef.current = operation;
|
||||
return operation;
|
||||
}, [enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh().finally(() => {
|
||||
if (mountedRef.current) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
});
|
||||
}, [refresh]);
|
||||
|
||||
const refreshOnAppActive = useEffectEvent(() => {
|
||||
void refresh();
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
const subscription = AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") {
|
||||
refreshOnAppActive();
|
||||
}
|
||||
});
|
||||
return () => subscription.remove();
|
||||
}, [enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!error) {
|
||||
return;
|
||||
}
|
||||
Alert.alert("Could not import shared content", error.message, [
|
||||
{ text: "Dismiss", style: "cancel", onPress: () => setError(null) },
|
||||
{
|
||||
text: "Retry",
|
||||
onPress: () => {
|
||||
setError(null);
|
||||
void refresh();
|
||||
},
|
||||
},
|
||||
]);
|
||||
}, [error, refresh]);
|
||||
|
||||
const consumeShare = useCallback(async (shareId: string) => {
|
||||
const snapshot = await incomingShareInbox.consume(shareId);
|
||||
if (mountedRef.current) {
|
||||
setDrafts(snapshot);
|
||||
}
|
||||
}, []);
|
||||
const reserveShare = useCallback(
|
||||
async (shareId: string, destination: IncomingShareDestination) => {
|
||||
const snapshot = await incomingShareInbox.reserve(shareId, destination);
|
||||
if (mountedRef.current) {
|
||||
setDrafts(snapshot);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
const releaseShareReservation = useCallback(
|
||||
async (shareId: string, expectedDestination: IncomingShareDestination) => {
|
||||
const snapshot = await incomingShareInbox.releaseReservation(shareId, expectedDestination);
|
||||
if (mountedRef.current) {
|
||||
setDrafts(snapshot);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
const getShare = useCallback(
|
||||
(shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null,
|
||||
[drafts],
|
||||
);
|
||||
|
||||
const value = useMemo<IncomingShareContextValue>(
|
||||
() => ({
|
||||
pendingShare: drafts[0] ?? null,
|
||||
isLoading,
|
||||
error,
|
||||
getShare,
|
||||
releaseShareReservation,
|
||||
reserveShare,
|
||||
consumeShare,
|
||||
refresh,
|
||||
}),
|
||||
[
|
||||
consumeShare,
|
||||
drafts,
|
||||
error,
|
||||
getShare,
|
||||
isLoading,
|
||||
refresh,
|
||||
releaseShareReservation,
|
||||
reserveShare,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<IncomingShareContext.Provider value={value}>{props.children}</IncomingShareContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useIncomingShare(): IncomingShareContextValue {
|
||||
const value = React.use(IncomingShareContext);
|
||||
if (value === null) {
|
||||
throw new Error("useIncomingShare must be used within IncomingShareProvider.");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import { describe, expect, it, vi } from "@effect/vitest";
|
||||
import type { SharePayload } from "expo-sharing";
|
||||
|
||||
import type { IncomingShareDraft } from "./incoming-share-model";
|
||||
import { IncomingShareInbox, type IncomingShareInboxDependencies } from "./incoming-share-inbox";
|
||||
|
||||
const PAYLOAD: SharePayload = {
|
||||
shareType: "text",
|
||||
mimeType: "text/plain",
|
||||
value: "Fix this",
|
||||
};
|
||||
|
||||
function draft(id: string, createdAt = "2026-07-16T08:00:00.000Z"): IncomingShareDraft {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
id,
|
||||
createdAt,
|
||||
text: PAYLOAD.value,
|
||||
attachments: [],
|
||||
warnings: [],
|
||||
};
|
||||
}
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>((next) => {
|
||||
resolve = next;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function createHarness(overrides: Partial<IncomingShareInboxDependencies> = {}) {
|
||||
const persisted = new Map<string, IncomingShareDraft>();
|
||||
let payloads: ReadonlyArray<SharePayload> = [PAYLOAD];
|
||||
const dependencies: IncomingShareInboxDependencies = {
|
||||
loadDrafts: async () => [...persisted.values()],
|
||||
writeDraft: async (value) => {
|
||||
persisted.set(value.id, value);
|
||||
},
|
||||
removeDraft: async (shareId) => {
|
||||
persisted.delete(shareId);
|
||||
},
|
||||
getPayloads: () => payloads,
|
||||
clearPayloads: () => {
|
||||
payloads = [];
|
||||
},
|
||||
buildDraft: async ({ id, createdAt }) => ({
|
||||
draft: draft(id, createdAt),
|
||||
cleanup: async () => undefined,
|
||||
}),
|
||||
idForPayloads: async () => "share-stable",
|
||||
now: () => "2026-07-16T08:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
return { inbox: new IncomingShareInbox(dependencies), persisted };
|
||||
}
|
||||
|
||||
describe("IncomingShareInbox", () => {
|
||||
it("coalesces a replay of an already-persisted native handoff", async () => {
|
||||
const buildDraft = vi.fn(async ({ id, createdAt }) => ({
|
||||
draft: draft(id, createdAt),
|
||||
cleanup: async () => undefined,
|
||||
}));
|
||||
const cleanupReplayedPayloads = vi.fn(async () => undefined);
|
||||
const { inbox, persisted } = createHarness({ buildDraft, cleanupReplayedPayloads });
|
||||
persisted.set("share-stable", draft("share-stable"));
|
||||
|
||||
await expect(inbox.refresh({ ingestNative: true })).resolves.toEqual([draft("share-stable")]);
|
||||
expect(buildDraft).not.toHaveBeenCalled();
|
||||
expect(cleanupReplayedPayloads).toHaveBeenCalledWith([PAYLOAD]);
|
||||
});
|
||||
|
||||
it("serializes concurrent refreshes so one native payload creates one inbox item", async () => {
|
||||
const building = deferred();
|
||||
const buildDraft = vi.fn(async ({ id, createdAt }) => {
|
||||
await building.promise;
|
||||
return { draft: draft(id, createdAt), cleanup: async () => undefined };
|
||||
});
|
||||
const { inbox } = createHarness({ buildDraft });
|
||||
|
||||
const first = inbox.refresh({ ingestNative: true });
|
||||
const second = inbox.refresh({ ingestNative: true });
|
||||
building.resolve();
|
||||
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([
|
||||
[draft("share-stable")],
|
||||
[draft("share-stable")],
|
||||
]);
|
||||
expect(buildDraft).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("orders consumption after an in-flight refresh without restoring stale state", async () => {
|
||||
const building = deferred();
|
||||
const { inbox, persisted } = createHarness({
|
||||
buildDraft: async ({ id, createdAt }) => {
|
||||
await building.promise;
|
||||
return { draft: draft(id, createdAt), cleanup: async () => undefined };
|
||||
},
|
||||
});
|
||||
|
||||
const refresh = inbox.refresh({ ingestNative: true });
|
||||
const consume = inbox.consume("share-stable");
|
||||
building.resolve();
|
||||
|
||||
await expect(refresh).resolves.toEqual([draft("share-stable")]);
|
||||
await expect(consume).resolves.toEqual([]);
|
||||
expect([...persisted.values()]).toEqual([]);
|
||||
});
|
||||
|
||||
it("consumes only the addressed share when another share has identical content", async () => {
|
||||
const { inbox, persisted } = createHarness();
|
||||
persisted.set("share-first", draft("share-first", "2026-07-16T07:59:00.000Z"));
|
||||
persisted.set("share-second", draft("share-second"));
|
||||
|
||||
await expect(inbox.refresh({ ingestNative: false })).resolves.toEqual([
|
||||
draft("share-second"),
|
||||
draft("share-first", "2026-07-16T07:59:00.000Z"),
|
||||
]);
|
||||
await expect(inbox.consume("share-second")).resolves.toEqual([
|
||||
draft("share-first", "2026-07-16T07:59:00.000Z"),
|
||||
]);
|
||||
expect([...persisted.values()]).toEqual([draft("share-first", "2026-07-16T07:59:00.000Z")]);
|
||||
});
|
||||
|
||||
it("keeps content-identical shares addressable by their own ids", async () => {
|
||||
const { inbox, persisted } = createHarness();
|
||||
persisted.set("share-open-flow", draft("share-open-flow", "2026-07-16T07:59:00.000Z"));
|
||||
persisted.set("share-newer", draft("share-newer"));
|
||||
|
||||
await expect(inbox.refresh({ ingestNative: false })).resolves.toEqual([
|
||||
draft("share-newer"),
|
||||
draft("share-open-flow", "2026-07-16T07:59:00.000Z"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not acknowledge a supported payload when its durable write fails", async () => {
|
||||
const clearPayloads = vi.fn();
|
||||
const cleanup = vi.fn(async () => undefined);
|
||||
const { inbox } = createHarness({
|
||||
clearPayloads,
|
||||
buildDraft: async ({ id, createdAt }) => ({
|
||||
draft: draft(id, createdAt),
|
||||
cleanup,
|
||||
}),
|
||||
writeDraft: async () => {
|
||||
throw new Error("disk full");
|
||||
},
|
||||
});
|
||||
|
||||
await expect(inbox.refresh({ ingestNative: true })).rejects.toThrow("disk full");
|
||||
expect(clearPayloads).not.toHaveBeenCalled();
|
||||
expect(cleanup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("durably reserves a share for one project before draft import", async () => {
|
||||
const { inbox, persisted } = createHarness();
|
||||
persisted.set("share-stable", draft("share-stable"));
|
||||
const destination = { environmentId: "environment-1", projectId: "project-1" };
|
||||
|
||||
await expect(inbox.reserve("share-stable", destination)).resolves.toEqual([
|
||||
{ ...draft("share-stable"), destination },
|
||||
]);
|
||||
expect(persisted.get("share-stable")?.destination).toEqual(destination);
|
||||
await expect(inbox.reserve("share-stable", destination)).resolves.toEqual([
|
||||
{ ...draft("share-stable"), destination },
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects moving a reserved share to another project", async () => {
|
||||
const { inbox, persisted } = createHarness();
|
||||
persisted.set("share-stable", {
|
||||
...draft("share-stable"),
|
||||
destination: { environmentId: "environment-1", projectId: "project-1" },
|
||||
});
|
||||
|
||||
await expect(
|
||||
inbox.reserve("share-stable", {
|
||||
environmentId: "environment-1",
|
||||
projectId: "project-2",
|
||||
}),
|
||||
).rejects.toThrow("already reserved");
|
||||
expect(persisted.get("share-stable")?.destination?.projectId).toBe("project-1");
|
||||
});
|
||||
|
||||
it("conditionally releases a reservation when its project is unavailable", async () => {
|
||||
const { inbox, persisted } = createHarness();
|
||||
const destination = { environmentId: "environment-1", projectId: "project-1" };
|
||||
persisted.set("share-stable", { ...draft("share-stable"), destination });
|
||||
|
||||
await expect(inbox.releaseReservation("share-stable", destination)).resolves.toEqual([
|
||||
draft("share-stable"),
|
||||
]);
|
||||
expect(persisted.get("share-stable")?.destination).toBeUndefined();
|
||||
|
||||
await expect(
|
||||
inbox.reserve("share-stable", {
|
||||
environmentId: "environment-2",
|
||||
projectId: "project-2",
|
||||
}),
|
||||
).resolves.toEqual([
|
||||
{
|
||||
...draft("share-stable"),
|
||||
destination: { environmentId: "environment-2", projectId: "project-2" },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not release a reservation that changed concurrently", async () => {
|
||||
const { inbox, persisted } = createHarness();
|
||||
persisted.set("share-stable", {
|
||||
...draft("share-stable"),
|
||||
destination: { environmentId: "environment-2", projectId: "project-2" },
|
||||
});
|
||||
|
||||
await expect(
|
||||
inbox.releaseReservation("share-stable", {
|
||||
environmentId: "environment-1",
|
||||
projectId: "project-1",
|
||||
}),
|
||||
).rejects.toThrow("reservation changed");
|
||||
expect(persisted.get("share-stable")?.destination?.projectId).toBe("project-2");
|
||||
});
|
||||
|
||||
it("treats an already-removed share as an already-released reservation", async () => {
|
||||
const { inbox, persisted } = createHarness();
|
||||
persisted.set("share-other", draft("share-other"));
|
||||
|
||||
await expect(
|
||||
inbox.releaseReservation("share-stable", {
|
||||
environmentId: "environment-1",
|
||||
projectId: "project-1",
|
||||
}),
|
||||
).resolves.toEqual([draft("share-other")]);
|
||||
expect([...persisted.values()]).toEqual([draft("share-other")]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
import type { SharePayload } from "expo-sharing";
|
||||
|
||||
import { SerializedAsyncQueue } from "../../lib/serialized-async-queue";
|
||||
import {
|
||||
hasIncomingShareContent,
|
||||
type IncomingShareDestination,
|
||||
type IncomingShareDraft,
|
||||
} from "./incoming-share-model";
|
||||
|
||||
export interface IncomingShareInboxDependencies {
|
||||
readonly loadDrafts: () => Promise<ReadonlyArray<IncomingShareDraft>>;
|
||||
readonly writeDraft: (draft: IncomingShareDraft) => Promise<void>;
|
||||
readonly removeDraft: (shareId: string) => Promise<void>;
|
||||
readonly getPayloads: () => ReadonlyArray<SharePayload>;
|
||||
readonly clearPayloads: () => void;
|
||||
readonly buildDraft: (input: {
|
||||
readonly payloads: ReadonlyArray<SharePayload>;
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
}) => Promise<{
|
||||
readonly draft: IncomingShareDraft;
|
||||
readonly cleanup: () => Promise<void>;
|
||||
}>;
|
||||
readonly cleanupReplayedPayloads?: (payloads: ReadonlyArray<SharePayload>) => Promise<void>;
|
||||
readonly idForPayloads: (payloads: ReadonlyArray<SharePayload>) => Promise<string>;
|
||||
readonly now: () => string;
|
||||
readonly onClearError?: (error: unknown) => void;
|
||||
readonly onCleanupError?: (error: unknown) => void;
|
||||
}
|
||||
|
||||
export function sortAndDedupeIncomingShares(
|
||||
drafts: ReadonlyArray<IncomingShareDraft>,
|
||||
): ReadonlyArray<IncomingShareDraft> {
|
||||
const ids = new Set<string>();
|
||||
return [...drafts]
|
||||
.sort((left, right) => right.createdAt.localeCompare(left.createdAt))
|
||||
.filter((draft) => {
|
||||
if (ids.has(draft.id)) {
|
||||
return false;
|
||||
}
|
||||
ids.add(draft.id);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes every durable inbox mutation. This prevents a stale storage load
|
||||
* or a foreground refresh from restoring an item after it has been consumed.
|
||||
*/
|
||||
export class IncomingShareInbox {
|
||||
private readonly operations = new SerializedAsyncQueue();
|
||||
|
||||
constructor(private readonly dependencies: IncomingShareInboxDependencies) {}
|
||||
|
||||
private runExclusive<T>(operation: () => Promise<T>): Promise<T> {
|
||||
return this.operations.run(operation);
|
||||
}
|
||||
|
||||
private clearNativePayloads(): void {
|
||||
try {
|
||||
this.dependencies.clearPayloads();
|
||||
} catch (error) {
|
||||
this.dependencies.onClearError?.(error);
|
||||
}
|
||||
}
|
||||
|
||||
private async cleanup(operation: () => Promise<void>): Promise<void> {
|
||||
try {
|
||||
await operation();
|
||||
} catch (error) {
|
||||
this.dependencies.onCleanupError?.(error);
|
||||
}
|
||||
}
|
||||
|
||||
refresh(options: { readonly ingestNative: boolean }): Promise<ReadonlyArray<IncomingShareDraft>> {
|
||||
return this.runExclusive(async () => {
|
||||
const loaded = await this.dependencies.loadDrafts();
|
||||
const persisted = sortAndDedupeIncomingShares(loaded);
|
||||
if (!options.ingestNative) {
|
||||
return persisted;
|
||||
}
|
||||
|
||||
const payloads = this.dependencies.getPayloads();
|
||||
if (payloads.length === 0) {
|
||||
return persisted;
|
||||
}
|
||||
|
||||
// A share extension payload remains available until the containing app
|
||||
// acknowledges it. Use a content-derived id so a crash after the durable
|
||||
// write but before acknowledgement reuses the same inbox item.
|
||||
const shareId = await this.dependencies.idForPayloads(payloads);
|
||||
if (loaded.some((draft) => draft.id === shareId)) {
|
||||
if (this.dependencies.cleanupReplayedPayloads) {
|
||||
await this.cleanup(() => this.dependencies.cleanupReplayedPayloads!(payloads));
|
||||
}
|
||||
this.clearNativePayloads();
|
||||
return persisted;
|
||||
}
|
||||
|
||||
const built = await this.dependencies.buildDraft({
|
||||
payloads,
|
||||
id: shareId,
|
||||
createdAt: this.dependencies.now(),
|
||||
});
|
||||
const { draft } = built;
|
||||
if (!hasIncomingShareContent(draft)) {
|
||||
// Unsupported native payloads cannot become actionable on retry and
|
||||
// would otherwise reopen the project picker on every foreground.
|
||||
await this.cleanup(built.cleanup);
|
||||
this.clearNativePayloads();
|
||||
throw new Error(
|
||||
draft.warnings[0] ?? "The shared content is not supported by the composer.",
|
||||
);
|
||||
}
|
||||
|
||||
// The durable inbox write is the transaction boundary. Never clear the
|
||||
// native handoff first: a process termination must leave one recoverable
|
||||
// copy on one side of the boundary.
|
||||
await this.dependencies.writeDraft(draft);
|
||||
await this.cleanup(built.cleanup);
|
||||
this.clearNativePayloads();
|
||||
return sortAndDedupeIncomingShares([draft, ...persisted]);
|
||||
});
|
||||
}
|
||||
|
||||
consume(shareId: string): Promise<ReadonlyArray<IncomingShareDraft>> {
|
||||
return this.runExclusive(async () => {
|
||||
// The stable payload-derived id already coalesces retries of the same
|
||||
// native handoff. Payload equality cannot identify duplicate handoffs:
|
||||
// users may intentionally share identical content more than once.
|
||||
await this.dependencies.removeDraft(shareId);
|
||||
return sortAndDedupeIncomingShares(await this.dependencies.loadDrafts());
|
||||
});
|
||||
}
|
||||
|
||||
reserve(
|
||||
shareId: string,
|
||||
destination: IncomingShareDestination,
|
||||
): Promise<ReadonlyArray<IncomingShareDraft>> {
|
||||
return this.runExclusive(async () => {
|
||||
const persisted = await this.dependencies.loadDrafts();
|
||||
const target = persisted.find((draft) => draft.id === shareId);
|
||||
if (!target) {
|
||||
throw new Error("The shared content is no longer available.");
|
||||
}
|
||||
if (target.destination) {
|
||||
if (
|
||||
target.destination.environmentId !== destination.environmentId ||
|
||||
target.destination.projectId !== destination.projectId
|
||||
) {
|
||||
throw new Error("The shared content is already reserved for another project draft.");
|
||||
}
|
||||
return sortAndDedupeIncomingShares(persisted);
|
||||
}
|
||||
|
||||
const reserved = { ...target, destination };
|
||||
await this.dependencies.writeDraft(reserved);
|
||||
return sortAndDedupeIncomingShares(
|
||||
persisted.map((draft) => (draft.id === shareId ? reserved : draft)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
releaseReservation(
|
||||
shareId: string,
|
||||
expectedDestination: IncomingShareDestination,
|
||||
): Promise<ReadonlyArray<IncomingShareDraft>> {
|
||||
return this.runExclusive(async () => {
|
||||
const persisted = await this.dependencies.loadDrafts();
|
||||
const target = persisted.find((draft) => draft.id === shareId);
|
||||
if (!target) {
|
||||
// Conditional release is idempotent: if another operation already
|
||||
// consumed the share, no reservation remains to clean up.
|
||||
return sortAndDedupeIncomingShares(persisted);
|
||||
}
|
||||
if (!target.destination) {
|
||||
return sortAndDedupeIncomingShares(persisted);
|
||||
}
|
||||
if (
|
||||
target.destination.environmentId !== expectedDestination.environmentId ||
|
||||
target.destination.projectId !== expectedDestination.projectId
|
||||
) {
|
||||
throw new Error("The shared content reservation changed before it could be released.");
|
||||
}
|
||||
|
||||
const { destination: _destination, ...unreserved } = target;
|
||||
await this.dependencies.writeDraft(unreserved);
|
||||
return sortAndDedupeIncomingShares(
|
||||
persisted.map((draft) => (draft.id === shareId ? unreserved : draft)),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { describe, expect, it, vi } from "@effect/vitest";
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ResolvedSharePayload, SharePayload } from "expo-sharing";
|
||||
|
||||
import { buildIncomingShareDraft, hasIncomingShareContent } from "./incoming-share-model";
|
||||
|
||||
describe("incoming native shares", () => {
|
||||
it("converts shared text, URLs, and images into a durable composer draft", async () => {
|
||||
const image: SharePayload = {
|
||||
shareType: "image",
|
||||
value: "file:///shared/Screenshot.png",
|
||||
mimeType: "image/png",
|
||||
};
|
||||
const payloads: SharePayload[] = [
|
||||
{ shareType: "text", value: "Please explain this error" },
|
||||
{ shareType: "url", value: "https://example.com/issue/1" },
|
||||
{ shareType: "text", value: "Please explain this error" },
|
||||
image,
|
||||
];
|
||||
const resolvedImage: ResolvedSharePayload = {
|
||||
...image,
|
||||
contentUri: image.value,
|
||||
contentType: "image",
|
||||
contentMimeType: "image/png",
|
||||
contentSize: 3,
|
||||
originalName: "Screenshot.png",
|
||||
};
|
||||
const removeOwnedFile = vi.fn(() => Promise.resolve());
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-1",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads,
|
||||
resolvedPayloads: [resolvedImage],
|
||||
fileReader: {
|
||||
readBase64: async () => "YWJj",
|
||||
removeOwnedFile,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
schemaVersion: 1,
|
||||
id: "share-1",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
text: "Please explain this error\n\nhttps://example.com/issue/1",
|
||||
attachments: [
|
||||
{
|
||||
id: "share-1:image:3",
|
||||
type: "image",
|
||||
name: "Screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 3,
|
||||
dataUrl: "data:image/png;base64,YWJj",
|
||||
previewUri: "data:image/png;base64,YWJj",
|
||||
},
|
||||
],
|
||||
warnings: [],
|
||||
});
|
||||
expect(removeOwnedFile).toHaveBeenCalledWith(image.value);
|
||||
expect(hasIncomingShareContent(result)).toBe(true);
|
||||
});
|
||||
|
||||
it("skips oversized images and releases the temporary native file", async () => {
|
||||
const image: SharePayload = {
|
||||
shareType: "image",
|
||||
value: "file:///shared/huge.png",
|
||||
mimeType: "image/png",
|
||||
};
|
||||
const readBase64 = vi.fn(async () => "unused");
|
||||
const removeOwnedFile = vi.fn(() => Promise.resolve());
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-2",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads: [image],
|
||||
resolvedPayloads: [
|
||||
{
|
||||
...image,
|
||||
contentUri: image.value,
|
||||
contentType: "image",
|
||||
contentMimeType: "image/png",
|
||||
contentSize: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
|
||||
originalName: "huge.png",
|
||||
},
|
||||
],
|
||||
fileReader: { readBase64, removeOwnedFile },
|
||||
});
|
||||
|
||||
expect(result.attachments).toEqual([]);
|
||||
expect(result.warnings).toEqual(["'huge.png' exceeds the 10 MB attachment limit."]);
|
||||
expect(readBase64).not.toHaveBeenCalled();
|
||||
expect(removeOwnedFile).toHaveBeenCalledWith(image.value);
|
||||
expect(hasIncomingShareContent(result)).toBe(false);
|
||||
});
|
||||
|
||||
it("releases every temporary file when a share exceeds the attachment limit", async () => {
|
||||
const payloads = Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS + 1 }, (_, index) => ({
|
||||
shareType: "image" as const,
|
||||
value: `file:///shared/${index}.png`,
|
||||
mimeType: "image/png",
|
||||
}));
|
||||
const removeOwnedFile = vi.fn(() => Promise.resolve());
|
||||
const readBase64 = vi.fn(async () => "YWJj");
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-3",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads,
|
||||
resolvedPayloads: [],
|
||||
fileReader: { readBase64, removeOwnedFile },
|
||||
});
|
||||
|
||||
expect(result.attachments).toHaveLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS);
|
||||
expect(result.warnings).toEqual([
|
||||
`Only the first ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} shared images were attached.`,
|
||||
]);
|
||||
expect(readBase64).toHaveBeenCalledTimes(PROVIDER_SEND_TURN_MAX_ATTACHMENTS);
|
||||
expect(removeOwnedFile).toHaveBeenCalledTimes(payloads.length);
|
||||
});
|
||||
|
||||
it("maps duplicate image payloads to distinct resolved files", async () => {
|
||||
const duplicate: SharePayload = {
|
||||
shareType: "image",
|
||||
value: "content://shared/screenshot",
|
||||
mimeType: "image/png",
|
||||
};
|
||||
const resolvedPayloads: ResolvedSharePayload[] = [
|
||||
{
|
||||
...duplicate,
|
||||
contentUri: "file:///cache/first.png",
|
||||
contentType: "image",
|
||||
contentMimeType: "image/png",
|
||||
contentSize: 3,
|
||||
originalName: "first.png",
|
||||
},
|
||||
{
|
||||
...duplicate,
|
||||
contentUri: "file:///cache/second.png",
|
||||
contentType: "image",
|
||||
contentMimeType: "image/png",
|
||||
contentSize: 3,
|
||||
originalName: "second.png",
|
||||
},
|
||||
];
|
||||
const readBase64 = vi.fn(async (uri: string) =>
|
||||
uri.includes("first") ? "Zmlyc3Q=" : "c2Vjb25k",
|
||||
);
|
||||
const removeOwnedFile = vi.fn(async () => undefined);
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-duplicates",
|
||||
createdAt: "2026-07-16T08:00:00.000Z",
|
||||
payloads: [duplicate, duplicate],
|
||||
resolvedPayloads,
|
||||
fileReader: { readBase64, removeOwnedFile },
|
||||
});
|
||||
|
||||
expect(readBase64.mock.calls.map(([uri]) => uri)).toEqual([
|
||||
"file:///cache/first.png",
|
||||
"file:///cache/second.png",
|
||||
]);
|
||||
expect(result.attachments.map((attachment) => attachment.name)).toEqual([
|
||||
"first.png",
|
||||
"second.png",
|
||||
]);
|
||||
expect(removeOwnedFile).toHaveBeenCalledWith("file:///cache/first.png");
|
||||
expect(removeOwnedFile).toHaveBeenCalledWith("file:///cache/second.png");
|
||||
});
|
||||
|
||||
it("keeps imported content when temporary-file cleanup fails", async () => {
|
||||
const image: SharePayload = {
|
||||
shareType: "image",
|
||||
value: "file:///shared/screenshot.png",
|
||||
mimeType: "image/png",
|
||||
};
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-cleanup-failure",
|
||||
createdAt: "2026-07-16T08:00:00.000Z",
|
||||
payloads: [image],
|
||||
resolvedPayloads: [],
|
||||
fileReader: {
|
||||
readBase64: async () => "YWJj",
|
||||
removeOwnedFile: async () => {
|
||||
throw new Error("file is busy");
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.attachments).toHaveLength(1);
|
||||
expect(result.warnings).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,217 @@
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type { ResolvedSharePayload, SharePayload } from "expo-sharing";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { estimateBase64ByteSize } from "../../lib/base64";
|
||||
|
||||
export interface IncomingShareDraft {
|
||||
readonly schemaVersion: 1;
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
readonly destination?: IncomingShareDestination;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly warnings: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export interface IncomingShareDestination {
|
||||
readonly environmentId: string;
|
||||
readonly projectId: string;
|
||||
}
|
||||
|
||||
const IncomingShareDestinationSchema = Schema.Struct({
|
||||
environmentId: Schema.String,
|
||||
projectId: Schema.String,
|
||||
});
|
||||
|
||||
export const IncomingShareDraftSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(1),
|
||||
id: Schema.String,
|
||||
createdAt: Schema.String,
|
||||
destination: Schema.optional(IncomingShareDestinationSchema),
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
warnings: Schema.Array(Schema.String),
|
||||
});
|
||||
|
||||
const decodeIncomingShareDraftSync = Schema.decodeUnknownSync(IncomingShareDraftSchema);
|
||||
|
||||
export function decodeIncomingShareDraft(value: unknown): IncomingShareDraft {
|
||||
return decodeIncomingShareDraftSync(value);
|
||||
}
|
||||
|
||||
export interface IncomingShareFileReader {
|
||||
readonly readBase64: (uri: string) => Promise<string>;
|
||||
readonly removeOwnedFile: (uri: string) => Promise<void> | void;
|
||||
}
|
||||
|
||||
function sharedText(payloads: ReadonlyArray<SharePayload>): string {
|
||||
const seen = new Set<string>();
|
||||
const values: string[] = [];
|
||||
for (const payload of payloads) {
|
||||
if (payload.shareType !== "text" && payload.shareType !== "url") {
|
||||
continue;
|
||||
}
|
||||
const value = payload.value.trim();
|
||||
if (!value || seen.has(value)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(value);
|
||||
values.push(value);
|
||||
}
|
||||
return values.join("\n\n");
|
||||
}
|
||||
|
||||
function resolvedImageFor(
|
||||
payload: SharePayload,
|
||||
index: number,
|
||||
resolvedPayloads: ReadonlyArray<ResolvedSharePayload>,
|
||||
consumedIndexes: Set<number>,
|
||||
): ResolvedSharePayload | undefined {
|
||||
const sameIndex = resolvedPayloads[index];
|
||||
if (
|
||||
!consumedIndexes.has(index) &&
|
||||
sameIndex?.shareType === payload.shareType &&
|
||||
sameIndex.value === payload.value
|
||||
) {
|
||||
consumedIndexes.add(index);
|
||||
return sameIndex;
|
||||
}
|
||||
const matchingIndex = resolvedPayloads.findIndex(
|
||||
(candidate, candidateIndex) =>
|
||||
!consumedIndexes.has(candidateIndex) &&
|
||||
candidate.shareType === payload.shareType &&
|
||||
candidate.value === payload.value,
|
||||
);
|
||||
if (matchingIndex < 0) {
|
||||
return undefined;
|
||||
}
|
||||
consumedIndexes.add(matchingIndex);
|
||||
return resolvedPayloads[matchingIndex];
|
||||
}
|
||||
|
||||
async function releaseOwnedFiles(
|
||||
fileReader: IncomingShareFileReader,
|
||||
uris: ReadonlyArray<string | undefined>,
|
||||
): Promise<void> {
|
||||
for (const uri of new Set(uris.filter((candidate): candidate is string => Boolean(candidate)))) {
|
||||
try {
|
||||
await fileReader.removeOwnedFile(uri);
|
||||
} catch {
|
||||
// Temporary-file cleanup is best-effort and must never discard content
|
||||
// that was successfully converted into a durable composer attachment.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function fallbackName(uri: string, index: number, mimeType: string): string {
|
||||
try {
|
||||
const pathName = new URL(uri).pathname.split("/").findLast((segment) => segment.length > 0);
|
||||
if (pathName) {
|
||||
return decodeURIComponent(pathName);
|
||||
}
|
||||
} catch {
|
||||
// Fall through to a deterministic attachment name.
|
||||
}
|
||||
const extension = mimeType.split("/")[1]?.replace(/[^a-z0-9.+-]/gi, "") || "png";
|
||||
return `shared-image-${index + 1}.${extension}`;
|
||||
}
|
||||
|
||||
export async function buildIncomingShareDraft(input: {
|
||||
readonly payloads: ReadonlyArray<SharePayload>;
|
||||
readonly resolvedPayloads: ReadonlyArray<ResolvedSharePayload>;
|
||||
readonly fileReader: IncomingShareFileReader;
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
}): Promise<IncomingShareDraft> {
|
||||
const attachments: DraftComposerImageAttachment[] = [];
|
||||
const warnings: string[] = [];
|
||||
const consumedResolvedPayloadIndexes = new Set<number>();
|
||||
let warnedAttachmentLimit = false;
|
||||
|
||||
for (const [index, payload] of input.payloads.entries()) {
|
||||
if (payload.shareType !== "image") {
|
||||
continue;
|
||||
}
|
||||
const resolved = resolvedImageFor(
|
||||
payload,
|
||||
index,
|
||||
input.resolvedPayloads,
|
||||
consumedResolvedPayloadIndexes,
|
||||
);
|
||||
const uri = resolved?.contentUri ?? payload.value;
|
||||
if (attachments.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
|
||||
if (!warnedAttachmentLimit) {
|
||||
warnings.push(
|
||||
`Only the first ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} shared images were attached.`,
|
||||
);
|
||||
warnedAttachmentLimit = true;
|
||||
}
|
||||
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
|
||||
continue;
|
||||
}
|
||||
|
||||
const mimeType = (resolved?.contentMimeType ?? payload.mimeType ?? "image/png").toLowerCase();
|
||||
if (!uri || !mimeType.startsWith("image/")) {
|
||||
warnings.push("One shared item was not a supported image.");
|
||||
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
resolved?.contentSize !== null &&
|
||||
resolved?.contentSize !== undefined &&
|
||||
resolved.contentSize > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
|
||||
) {
|
||||
warnings.push(
|
||||
`'${resolved.originalName ?? fallbackName(uri, index, mimeType)}' exceeds the 10 MB attachment limit.`,
|
||||
);
|
||||
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const base64 = await input.fileReader.readBase64(uri);
|
||||
const sizeBytes = resolved?.contentSize ?? estimateBase64ByteSize(base64);
|
||||
if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
|
||||
warnings.push(
|
||||
`'${resolved?.originalName ?? fallbackName(uri, index, mimeType)}' exceeds the 10 MB attachment limit.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const dataUrl = `data:${mimeType};base64,${base64}`;
|
||||
attachments.push({
|
||||
id: `${input.id}:image:${index}`,
|
||||
type: "image",
|
||||
name: resolved?.originalName ?? fallbackName(uri, index, mimeType),
|
||||
mimeType,
|
||||
sizeBytes,
|
||||
dataUrl,
|
||||
// The share provider's file is temporary. A data-backed preview keeps
|
||||
// the composer valid after its source file and App Group entry are gone.
|
||||
previewUri: dataUrl,
|
||||
});
|
||||
} catch {
|
||||
warnings.push(`Could not read '${fallbackName(uri, index, mimeType)}'.`);
|
||||
} finally {
|
||||
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
id: input.id,
|
||||
createdAt: input.createdAt,
|
||||
text: sharedText(input.payloads),
|
||||
attachments,
|
||||
warnings,
|
||||
};
|
||||
}
|
||||
|
||||
export function hasIncomingShareContent(draft: IncomingShareDraft): boolean {
|
||||
return draft.text.trim().length > 0 || draft.attachments.length > 0;
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
|
||||
transitionIncomingSharePresentation,
|
||||
} from "./incoming-share-presentation";
|
||||
|
||||
describe("incoming share presentation", () => {
|
||||
it("does not reopen a dismissed share when refresh returns a new object for the same id", () => {
|
||||
const presented = transitionIncomingSharePresentation(EMPTY_INCOMING_SHARE_PRESENTATION_STATE, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: "share-1",
|
||||
});
|
||||
expect(presented.shareIdToPresent).toBe("share-1");
|
||||
|
||||
const whilePresented = transitionIncomingSharePresentation(presented.state, {
|
||||
isShareSheetPresented: true,
|
||||
pendingShareId: "share-1",
|
||||
});
|
||||
expect(whilePresented).toEqual({ state: presented.state, shareIdToPresent: null });
|
||||
|
||||
const dismissed = transitionIncomingSharePresentation(whilePresented.state, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: "share-1",
|
||||
});
|
||||
expect(dismissed.state.dismissedShareId).toBe("share-1");
|
||||
|
||||
expect(
|
||||
transitionIncomingSharePresentation(dismissed.state, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: "share-1",
|
||||
}),
|
||||
).toEqual({ state: dismissed.state, shareIdToPresent: null });
|
||||
});
|
||||
|
||||
it("presents the next queued share immediately after the previous sheet closes", () => {
|
||||
const first = transitionIncomingSharePresentation(EMPTY_INCOMING_SHARE_PRESENTATION_STATE, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: "share-1",
|
||||
});
|
||||
|
||||
const next = transitionIncomingSharePresentation(first.state, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: "share-2",
|
||||
});
|
||||
expect(next.shareIdToPresent).toBe("share-2");
|
||||
expect(next.state).toEqual({ presentedShareId: "share-2", dismissedShareId: null });
|
||||
});
|
||||
|
||||
it("forgets dismissal after consumption so a later handoff may reuse the id", () => {
|
||||
const dismissed = {
|
||||
presentedShareId: null,
|
||||
dismissedShareId: "share-1",
|
||||
};
|
||||
const consumed = transitionIncomingSharePresentation(dismissed, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: null,
|
||||
});
|
||||
expect(consumed.state).toEqual(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
|
||||
|
||||
expect(
|
||||
transitionIncomingSharePresentation(consumed.state, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: "share-1",
|
||||
}).shareIdToPresent,
|
||||
).toBe("share-1");
|
||||
});
|
||||
|
||||
it("forgets a consumed presentation while its sheet is still mounted", () => {
|
||||
const presented = {
|
||||
presentedShareId: "share-1",
|
||||
dismissedShareId: null,
|
||||
};
|
||||
const consumed = transitionIncomingSharePresentation(presented, {
|
||||
isShareSheetPresented: true,
|
||||
pendingShareId: null,
|
||||
});
|
||||
expect(consumed.state).toEqual(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
|
||||
|
||||
const replacementWhileOpen = transitionIncomingSharePresentation(consumed.state, {
|
||||
isShareSheetPresented: true,
|
||||
pendingShareId: "share-1",
|
||||
});
|
||||
expect(replacementWhileOpen.shareIdToPresent).toBeNull();
|
||||
expect(
|
||||
transitionIncomingSharePresentation(replacementWhileOpen.state, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: "share-1",
|
||||
}).shareIdToPresent,
|
||||
).toBe("share-1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
export interface IncomingSharePresentationState {
|
||||
readonly presentedShareId: string | null;
|
||||
readonly dismissedShareId: string | null;
|
||||
}
|
||||
|
||||
export interface IncomingSharePresentationTransition {
|
||||
readonly state: IncomingSharePresentationState;
|
||||
readonly shareIdToPresent: string | null;
|
||||
}
|
||||
|
||||
export const EMPTY_INCOMING_SHARE_PRESENTATION_STATE: IncomingSharePresentationState = {
|
||||
presentedShareId: null,
|
||||
dismissedShareId: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* Tracks presentation by durable share id rather than object identity. A user
|
||||
* dismissal suppresses only that inbox item until it is consumed or replaced.
|
||||
*/
|
||||
export function transitionIncomingSharePresentation(
|
||||
state: IncomingSharePresentationState,
|
||||
input: {
|
||||
readonly isShareSheetPresented: boolean;
|
||||
readonly pendingShareId: string | null;
|
||||
},
|
||||
): IncomingSharePresentationTransition {
|
||||
if (input.isShareSheetPresented) {
|
||||
if (state.presentedShareId !== null && input.pendingShareId !== state.presentedShareId) {
|
||||
// Consumption may happen while the sheet remains mounted. Forget the
|
||||
// old presentation immediately so a later handoff may reuse its id.
|
||||
return {
|
||||
state: EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
|
||||
shareIdToPresent: null,
|
||||
};
|
||||
}
|
||||
return { state, shareIdToPresent: null };
|
||||
}
|
||||
|
||||
let nextState = state;
|
||||
if (state.presentedShareId !== null) {
|
||||
if (input.pendingShareId === state.presentedShareId) {
|
||||
return {
|
||||
state: {
|
||||
presentedShareId: null,
|
||||
dismissedShareId: state.presentedShareId,
|
||||
},
|
||||
shareIdToPresent: null,
|
||||
};
|
||||
}
|
||||
nextState = { ...state, presentedShareId: null };
|
||||
}
|
||||
|
||||
if (input.pendingShareId === null) {
|
||||
return {
|
||||
state: EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
|
||||
shareIdToPresent: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (nextState.dismissedShareId === input.pendingShareId) {
|
||||
return { state: nextState, shareIdToPresent: null };
|
||||
}
|
||||
|
||||
return {
|
||||
state: {
|
||||
presentedShareId: input.pendingShareId,
|
||||
dismissedShareId: null,
|
||||
},
|
||||
shareIdToPresent: input.pendingShareId,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { decodeIncomingShareDraft, type IncomingShareDraft } from "./incoming-share-model";
|
||||
|
||||
const INCOMING_SHARE_DIRECTORY = "incoming-shares";
|
||||
|
||||
export class IncomingShareStorageError extends Schema.TaggedErrorClass<IncomingShareStorageError>()(
|
||||
"IncomingShareStorageError",
|
||||
{
|
||||
operation: Schema.Literals(["load", "write", "remove"]),
|
||||
shareId: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Incoming share storage operation ${this.operation} failed for ${this.shareId ?? "unknown"}.`;
|
||||
}
|
||||
}
|
||||
|
||||
function fileName(shareId: string): string {
|
||||
return `${encodeURIComponent(shareId)}.json`;
|
||||
}
|
||||
|
||||
async function getDirectory() {
|
||||
const { Directory, Paths } = await import("expo-file-system");
|
||||
const directory = new Directory(Paths.document, INCOMING_SHARE_DIRECTORY);
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
return directory;
|
||||
}
|
||||
|
||||
async function getFile(shareId: string) {
|
||||
const { File } = await import("expo-file-system");
|
||||
return new File(await getDirectory(), fileName(shareId));
|
||||
}
|
||||
|
||||
export async function loadIncomingShareDrafts(): Promise<ReadonlyArray<IncomingShareDraft>> {
|
||||
try {
|
||||
const { File } = await import("expo-file-system");
|
||||
const drafts: IncomingShareDraft[] = [];
|
||||
for (const entry of (await getDirectory()).list()) {
|
||||
if (!(entry instanceof File) || !entry.name.endsWith(".json")) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
drafts.push(decodeIncomingShareDraft(JSON.parse(await entry.text()) as unknown));
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[incoming-share] ignored invalid persisted share",
|
||||
new IncomingShareStorageError({ operation: "load", shareId: null, cause }),
|
||||
);
|
||||
}
|
||||
}
|
||||
return drafts.sort((left, right) => right.createdAt.localeCompare(left.createdAt));
|
||||
} catch (cause) {
|
||||
throw new IncomingShareStorageError({ operation: "load", shareId: null, cause });
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeIncomingShareDraft(draft: IncomingShareDraft): Promise<void> {
|
||||
try {
|
||||
const file = await getFile(draft.id);
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(draft));
|
||||
} catch (cause) {
|
||||
throw new IncomingShareStorageError({ operation: "write", shareId: draft.id, cause });
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeIncomingShareDraft(shareId: string): Promise<void> {
|
||||
try {
|
||||
const file = await getFile(shareId);
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
} catch (cause) {
|
||||
throw new IncomingShareStorageError({ operation: "remove", shareId, cause });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Keyboard, View } from "react-native";
|
||||
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { useConnectionController } from "../connection/useConnectionController";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
import { holdEditingQueuedMessage } from "../../state/use-thread-outbox";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import {
|
||||
getNativeShowcasePairingUrls,
|
||||
getNativeShowcaseScene,
|
||||
markNativeShowcaseReady,
|
||||
type ShowcaseScene,
|
||||
} from "./nativeShowcaseScene";
|
||||
import {
|
||||
buildShowcasePendingTasks,
|
||||
SHOWCASE_PENDING_TASK_DEFINITIONS,
|
||||
} from "./showcasePendingTasks";
|
||||
import { retryShowcaseOperation } from "./showcaseRetry";
|
||||
|
||||
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
|
||||
const SHOWCASE_THREAD_ID = "remote-command-center";
|
||||
|
||||
function sceneFromPathname(pathname: string): ShowcaseScene | null {
|
||||
const routePath = pathname.split(/[?#]/u, 1)[0] ?? pathname;
|
||||
if (routePath === "/settings" || routePath.endsWith("/settings/environments")) {
|
||||
return "environments";
|
||||
}
|
||||
if (routePath.endsWith("/terminal")) return "terminal";
|
||||
if (routePath.endsWith("/review")) return "review";
|
||||
if (routePath.startsWith("/threads/")) return "thread";
|
||||
if (routePath === "/") return "threads";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function ShowcaseCaptureCoordinator(props: { readonly pathname: string }) {
|
||||
const navigation = useNavigation();
|
||||
const { connectPairingUrl } = useConnectionController();
|
||||
const workspace = useWorkspaceState();
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const attemptedPairingRef = useRef(new Set<string>());
|
||||
const seededPendingTaskIdsRef = useRef(new Set<string>());
|
||||
const [pairingUrls, setPairingUrls] = useState<ReadonlyArray<string>>([]);
|
||||
const [pendingTasksReady, setPendingTasksReady] = useState(false);
|
||||
const [requestedScene, setRequestedScene] = useState<ShowcaseScene | null>(null);
|
||||
const [readyScene, setReadyScene] = useState<ShowcaseScene | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED || pairingUrls.length > 0) return;
|
||||
|
||||
const readPairingUrls = () => {
|
||||
const values = getNativeShowcasePairingUrls();
|
||||
if (values.length > 0) setPairingUrls(values);
|
||||
};
|
||||
readPairingUrls();
|
||||
const interval = setInterval(readPairingUrls, 250);
|
||||
return () => clearInterval(interval);
|
||||
}, [pairingUrls.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED) return;
|
||||
|
||||
const readRequestedScene = () => {
|
||||
const value = getNativeShowcaseScene();
|
||||
if (value) setRequestedScene(value);
|
||||
};
|
||||
readRequestedScene();
|
||||
const interval = setInterval(readRequestedScene, 250);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED || pairingUrls.length === 0) return;
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
await Promise.all(
|
||||
pairingUrls.map(async (pairingUrl) => {
|
||||
if (cancelled || attemptedPairingRef.current.has(pairingUrl)) return;
|
||||
const paired = await retryShowcaseOperation(
|
||||
async () => AsyncResult.isSuccess(await connectPairingUrl(pairingUrl)),
|
||||
{ isCancelled: () => cancelled },
|
||||
);
|
||||
if (paired) attemptedPairingRef.current.add(pairingUrl);
|
||||
}),
|
||||
);
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [connectPairingUrl, pairingUrls]);
|
||||
|
||||
const scene = sceneFromPathname(props.pathname);
|
||||
const hasServerFixture =
|
||||
workspace.state.hasReadyEnvironment &&
|
||||
workspace.environments.length >= 3 &&
|
||||
projects.length >= 3 &&
|
||||
threads.some((thread) => String(thread.id) === SHOWCASE_THREAD_ID);
|
||||
const hasFixture = hasServerFixture && pendingTasksReady;
|
||||
const showcaseThread = threads.find((thread) => String(thread.id) === SHOWCASE_THREAD_ID);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED || !hasServerFixture || pendingTasksReady) return;
|
||||
|
||||
const pendingTasks = buildShowcasePendingTasks(projects, Date.now());
|
||||
if (pendingTasks.length !== SHOWCASE_PENDING_TASK_DEFINITIONS.length) return;
|
||||
|
||||
let cancelled = false;
|
||||
for (const task of pendingTasks) holdEditingQueuedMessage(task.messageId);
|
||||
void (async () => {
|
||||
const results = await Promise.all(
|
||||
pendingTasks.map(async (task) => {
|
||||
const messageId = String(task.messageId);
|
||||
if (seededPendingTaskIdsRef.current.has(messageId)) return true;
|
||||
const seeded = await retryShowcaseOperation(
|
||||
async () => {
|
||||
await enqueueThreadOutboxMessage(task);
|
||||
return true;
|
||||
},
|
||||
{ isCancelled: () => cancelled },
|
||||
);
|
||||
if (seeded) seededPendingTaskIdsRef.current.add(messageId);
|
||||
return seeded;
|
||||
}),
|
||||
);
|
||||
if (!cancelled && results.every(Boolean)) setPendingTasksReady(true);
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [hasServerFixture, pendingTasksReady, projects]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED || requestedScene === null || !hasFixture || !showcaseThread) return;
|
||||
if (scene === requestedScene) return;
|
||||
|
||||
const params = {
|
||||
environmentId: String(showcaseThread.environmentId),
|
||||
threadId: SHOWCASE_THREAD_ID,
|
||||
};
|
||||
if (requestedScene === "threads") {
|
||||
navigation.dispatch(StackActions.popToTop());
|
||||
return;
|
||||
}
|
||||
const routes: Array<{
|
||||
name: string;
|
||||
params?: Record<string, unknown>;
|
||||
state?: { index: number; routes: Array<{ name: string }> };
|
||||
}> = [{ name: "Home" }];
|
||||
if (requestedScene === "environments") {
|
||||
routes.push({
|
||||
name: "SettingsSheet",
|
||||
state: {
|
||||
index: 1,
|
||||
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
|
||||
},
|
||||
});
|
||||
} else {
|
||||
routes.push({ name: "Thread", params });
|
||||
if (requestedScene === "terminal") {
|
||||
routes.push({
|
||||
name: "ThreadTerminal",
|
||||
params: { ...params, terminalId: "term-1" },
|
||||
});
|
||||
} else if (requestedScene === "review") {
|
||||
routes.push({ name: "ThreadReview", params });
|
||||
}
|
||||
}
|
||||
navigation.dispatch(
|
||||
CommonActions.reset({
|
||||
index: routes.length - 1,
|
||||
routes,
|
||||
}),
|
||||
);
|
||||
}, [hasFixture, navigation, requestedScene, scene, showcaseThread]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!SHOWCASE_ENABLED ||
|
||||
scene === null ||
|
||||
requestedScene === null ||
|
||||
scene !== requestedScene ||
|
||||
!hasFixture
|
||||
) {
|
||||
setReadyScene(null);
|
||||
return;
|
||||
}
|
||||
// Review owns its readiness marker because route activation happens before
|
||||
// the VCS request is parsed and the native diff surface is mounted.
|
||||
if (scene === "review") {
|
||||
setReadyScene(null);
|
||||
return;
|
||||
}
|
||||
if (scene === "terminal") Keyboard.dismiss();
|
||||
|
||||
let renderFrame: number | null = null;
|
||||
let readyFrame: number | null = null;
|
||||
const settleTimer = setTimeout(() => {
|
||||
renderFrame = requestAnimationFrame(() => {
|
||||
readyFrame = requestAnimationFrame(() => {
|
||||
markNativeShowcaseReady(scene);
|
||||
setReadyScene(scene);
|
||||
});
|
||||
});
|
||||
}, 500);
|
||||
return () => {
|
||||
clearTimeout(settleTimer);
|
||||
if (renderFrame !== null) cancelAnimationFrame(renderFrame);
|
||||
if (readyFrame !== null) cancelAnimationFrame(readyFrame);
|
||||
};
|
||||
}, [hasFixture, requestedScene, scene]);
|
||||
|
||||
if (!SHOWCASE_ENABLED || readyScene === null) return null;
|
||||
|
||||
return (
|
||||
<View
|
||||
pointerEvents="none"
|
||||
testID={`showcase-ready-${readyScene}`}
|
||||
style={{ position: "absolute", width: 1, height: 1, opacity: 0.01 }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { requireOptionalNativeModule } from "expo";
|
||||
|
||||
export const SHOWCASE_SCENES = ["threads", "thread", "terminal", "review", "environments"] as const;
|
||||
export type ShowcaseScene = (typeof SHOWCASE_SCENES)[number];
|
||||
|
||||
interface NativeShowcaseControls {
|
||||
readonly getShowcasePairingUrl?: () => string | null;
|
||||
readonly getShowcaseScene?: () => string | null;
|
||||
readonly prepareShowcaseCapture?: () => void;
|
||||
readonly markShowcaseReady?: (scene: ShowcaseScene) => void;
|
||||
}
|
||||
|
||||
function nativeShowcaseControls(): NativeShowcaseControls | null {
|
||||
return requireOptionalNativeModule<NativeShowcaseControls>("T3NativeControls");
|
||||
}
|
||||
|
||||
export function getNativeShowcasePairingUrls(): ReadonlyArray<string> {
|
||||
try {
|
||||
let raw = nativeShowcaseControls()?.getShowcasePairingUrl?.()?.trim();
|
||||
if (!raw) return [];
|
||||
if (raw.startsWith("json-uri:")) {
|
||||
try {
|
||||
raw = decodeURIComponent(raw.slice("json-uri:".length));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed.filter(
|
||||
(candidate): candidate is string =>
|
||||
typeof candidate === "string" && candidate.trim().length > 0,
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// Older runners pass a single URL rather than a JSON array.
|
||||
}
|
||||
return [raw];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function getNativeShowcaseScene(): ShowcaseScene | null {
|
||||
try {
|
||||
const scene = nativeShowcaseControls()?.getShowcaseScene?.()?.trim();
|
||||
return SHOWCASE_SCENES.find((candidate) => candidate === scene) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function prepareNativeShowcaseCapture(): void {
|
||||
try {
|
||||
nativeShowcaseControls()?.prepareShowcaseCapture?.();
|
||||
} catch {
|
||||
// The harness still works when a development build predates this helper.
|
||||
}
|
||||
}
|
||||
|
||||
export function markNativeShowcaseReady(scene: ShowcaseScene): void {
|
||||
try {
|
||||
nativeShowcaseControls()?.markShowcaseReady?.(scene);
|
||||
} catch {
|
||||
// The readiness marker is capture-runner metadata, never app functionality.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
|
||||
import {
|
||||
applyShowcaseLocalEnvironmentDisplayUrls,
|
||||
resolveShowcaseEnvironmentUpdateDisplayUrl,
|
||||
} from "./showcaseEnvironmentRows";
|
||||
|
||||
function environment(
|
||||
environmentId: string,
|
||||
environmentLabel: string,
|
||||
displayUrl = "http://127.0.0.1:3773/",
|
||||
): ConnectedEnvironmentSummary {
|
||||
return {
|
||||
environmentId: EnvironmentId.make(environmentId),
|
||||
environmentLabel,
|
||||
displayUrl,
|
||||
isRelayManaged: false,
|
||||
connectionState: "connected",
|
||||
connectionError: null,
|
||||
connectionErrorTraceId: null,
|
||||
};
|
||||
}
|
||||
|
||||
it("presents showcase transports as remote endpoints", () => {
|
||||
const environments = applyShowcaseLocalEnvironmentDisplayUrls([
|
||||
environment("runtime-id-1", "Moonbase Terminal"),
|
||||
environment("runtime-id-2", "Suspense Station"),
|
||||
environment("runtime-id-3", "Kernel Cabin"),
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
environments.map(({ displayUrl }) => displayUrl),
|
||||
[
|
||||
"https://moonbase.tail9f3a.ts.net/",
|
||||
"https://suspense-vps.hel1.t3.sh/",
|
||||
"http://100.82.16.5:3773/",
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves environments outside the showcase fixture unchanged", () => {
|
||||
const original = environment(
|
||||
"runtime-id-4",
|
||||
"My Workstation",
|
||||
"https://workstation.example.test/",
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(applyShowcaseLocalEnvironmentDisplayUrls([original]), [original]);
|
||||
});
|
||||
|
||||
it("does not persist a cosmetic showcase URL when only the label is saved", () => {
|
||||
assert.equal(
|
||||
resolveShowcaseEnvironmentUpdateDisplayUrl({
|
||||
actualDisplayUrl: "http://127.0.0.1:3773/",
|
||||
presentedDisplayUrl: "https://moonbase.tail9f3a.ts.net/",
|
||||
submittedDisplayUrl: "https://moonbase.tail9f3a.ts.net/",
|
||||
}),
|
||||
"http://127.0.0.1:3773/",
|
||||
);
|
||||
assert.equal(
|
||||
resolveShowcaseEnvironmentUpdateDisplayUrl({
|
||||
actualDisplayUrl: "http://127.0.0.1:3773/",
|
||||
presentedDisplayUrl: "https://moonbase.tail9f3a.ts.net/",
|
||||
submittedDisplayUrl: "https://new-host.example.com/",
|
||||
}),
|
||||
"https://new-host.example.com/",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
import type { RelayEnvironmentView } from "../connection/useConnectionController";
|
||||
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
|
||||
|
||||
const SHOWCASE_LOCAL_ENVIRONMENT_DISPLAY_URLS: Readonly<Record<string, string>> = {
|
||||
"Moonbase Terminal": "https://moonbase.tail9f3a.ts.net/",
|
||||
"Suspense Station": "https://suspense-vps.hel1.t3.sh/",
|
||||
"Kernel Cabin": "http://100.82.16.5:3773/",
|
||||
};
|
||||
|
||||
export function applyShowcaseLocalEnvironmentDisplayUrls(
|
||||
environments: ReadonlyArray<ConnectedEnvironmentSummary>,
|
||||
): ReadonlyArray<ConnectedEnvironmentSummary> {
|
||||
return environments.map((environment) => ({
|
||||
...environment,
|
||||
displayUrl:
|
||||
SHOWCASE_LOCAL_ENVIRONMENT_DISPLAY_URLS[environment.environmentLabel] ??
|
||||
environment.displayUrl,
|
||||
}));
|
||||
}
|
||||
|
||||
export function resolveShowcaseEnvironmentUpdateDisplayUrl(input: {
|
||||
readonly actualDisplayUrl: string;
|
||||
readonly presentedDisplayUrl: string;
|
||||
readonly submittedDisplayUrl: string;
|
||||
}): string {
|
||||
return input.submittedDisplayUrl === input.presentedDisplayUrl
|
||||
? input.actualDisplayUrl
|
||||
: input.submittedDisplayUrl;
|
||||
}
|
||||
|
||||
const pocketPiId = EnvironmentId.make("showcase-pocket-pi");
|
||||
const pocketPiEndpoint = {
|
||||
httpBaseUrl: "https://pocket-pi.t3.sh",
|
||||
wsBaseUrl: "wss://pocket-pi.t3.sh",
|
||||
providerKind: "t3_relay" as const,
|
||||
};
|
||||
|
||||
export const SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS: ReadonlyArray<ConnectedEnvironmentSummary> = [
|
||||
{
|
||||
environmentId: EnvironmentId.make("showcase-aurora-gpu"),
|
||||
environmentLabel: "Aurora GPU Pod",
|
||||
displayUrl: "https://aurora-gpu.t3.sh",
|
||||
isRelayManaged: true,
|
||||
connectionState: "connected",
|
||||
connectionError: null,
|
||||
connectionErrorTraceId: null,
|
||||
},
|
||||
];
|
||||
|
||||
export const SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS: ReadonlyArray<RelayEnvironmentView> = [
|
||||
{
|
||||
environment: {
|
||||
environmentId: pocketPiId,
|
||||
label: "Pocket Pi",
|
||||
endpoint: pocketPiEndpoint,
|
||||
linkedAt: "2026-07-16T08:00:00.000Z",
|
||||
},
|
||||
availability: "online",
|
||||
status: {
|
||||
environmentId: pocketPiId,
|
||||
endpoint: pocketPiEndpoint,
|
||||
status: "online",
|
||||
checkedAt: "2026-07-16T08:41:00.000Z",
|
||||
},
|
||||
error: null,
|
||||
traceId: null,
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
buildShowcasePendingTasks,
|
||||
SHOWCASE_PENDING_TASK_DEFINITIONS,
|
||||
} from "./showcasePendingTasks";
|
||||
|
||||
const projects: ReadonlyArray<EnvironmentProject> = [
|
||||
{
|
||||
environmentId: EnvironmentId.make("moonbase-terminal"),
|
||||
id: ProjectId.make("t3code"),
|
||||
title: "T3 Code",
|
||||
workspaceRoot: "/workspace/t3code",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
scripts: [],
|
||||
createdAt: "2026-07-16T08:00:00.000Z",
|
||||
updatedAt: "2026-07-16T08:00:00.000Z",
|
||||
},
|
||||
{
|
||||
environmentId: EnvironmentId.make("suspense-station"),
|
||||
id: ProjectId.make("react"),
|
||||
title: "React",
|
||||
workspaceRoot: "/workspace/react",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-07-16T08:00:00.000Z",
|
||||
updatedAt: "2026-07-16T08:00:00.000Z",
|
||||
},
|
||||
];
|
||||
|
||||
it("builds sendable-looking pending tasks against real showcase projects", () => {
|
||||
const tasks = buildShowcasePendingTasks(projects, Date.parse("2026-07-16T09:00:00.000Z"));
|
||||
|
||||
assert.equal(tasks.length, SHOWCASE_PENDING_TASK_DEFINITIONS.length);
|
||||
assert.deepStrictEqual(
|
||||
tasks.map((task) => ({
|
||||
environmentId: String(task.environmentId),
|
||||
projectId: task.creation ? String(task.creation.projectId) : undefined,
|
||||
title: task.creation?.projectTitle,
|
||||
branch: task.creation?.branch,
|
||||
createdAt: task.createdAt,
|
||||
})),
|
||||
[
|
||||
{
|
||||
environmentId: "moonbase-terminal",
|
||||
projectId: "t3code",
|
||||
title: "T3 Code",
|
||||
branch: "feat/offline-launchpad",
|
||||
createdAt: "2026-07-16T08:52:00.000Z",
|
||||
},
|
||||
{
|
||||
environmentId: "suspense-station",
|
||||
projectId: "react",
|
||||
title: "React",
|
||||
branch: "perf/tunnel-handoff",
|
||||
createdAt: "2026-07-16T08:33:00.000Z",
|
||||
},
|
||||
],
|
||||
);
|
||||
assert.equal(
|
||||
tasks.every((task) => task.modelSelection !== undefined),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("waits until every referenced project has hydrated", () => {
|
||||
assert.equal(buildShowcasePendingTasks(projects.slice(0, 1), Date.now()).length, 1);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
MessageId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
|
||||
|
||||
export const SHOWCASE_PENDING_TASK_DEFINITIONS = [
|
||||
{
|
||||
projectId: "t3code",
|
||||
id: "offline-launch-checklist",
|
||||
text: "Ship the offline launch checklist before touchdown ✈️",
|
||||
branch: "feat/offline-launchpad",
|
||||
minutesAgo: 8,
|
||||
},
|
||||
{
|
||||
projectId: "react",
|
||||
id: "train-tunnel-suspense",
|
||||
text: "Polish the Suspense handoff for the train tunnel 🚇",
|
||||
branch: "perf/tunnel-handoff",
|
||||
minutesAgo: 27,
|
||||
},
|
||||
] as const;
|
||||
|
||||
const FALLBACK_MODEL_SELECTION = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
} as const;
|
||||
|
||||
export function buildShowcasePendingTasks(
|
||||
projects: ReadonlyArray<EnvironmentProject>,
|
||||
now: number,
|
||||
): ReadonlyArray<QueuedThreadMessage> {
|
||||
return SHOWCASE_PENDING_TASK_DEFINITIONS.flatMap((definition) => {
|
||||
const project = projects.find((candidate) => String(candidate.id) === definition.projectId);
|
||||
if (!project) return [];
|
||||
|
||||
return [
|
||||
{
|
||||
environmentId: project.environmentId,
|
||||
threadId: ThreadId.make(`showcase-pending-${definition.id}`),
|
||||
messageId: MessageId.make(`showcase-pending-message-${definition.id}`),
|
||||
commandId: CommandId.make(`showcase-pending-command-${definition.id}`),
|
||||
text: definition.text,
|
||||
attachments: [],
|
||||
modelSelection: project.defaultModelSelection ?? FALLBACK_MODEL_SELECTION,
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
creation: {
|
||||
projectId: project.id,
|
||||
projectTitle: project.title,
|
||||
projectCwd: project.workspaceRoot,
|
||||
workspaceMode: "local" as const,
|
||||
branch: definition.branch,
|
||||
worktreePath: project.workspaceRoot,
|
||||
},
|
||||
createdAt: new Date(now - definition.minutesAgo * 60_000).toISOString(),
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { retryShowcaseOperation } from "./showcaseRetry";
|
||||
|
||||
it("retries a failed showcase operation until it succeeds", async () => {
|
||||
let attempts = 0;
|
||||
const succeeded = await retryShowcaseOperation(
|
||||
async () => {
|
||||
attempts += 1;
|
||||
return attempts === 3;
|
||||
},
|
||||
{ isCancelled: () => false, retryDelayMs: 0 },
|
||||
);
|
||||
|
||||
assert.equal(succeeded, true);
|
||||
assert.equal(attempts, 3);
|
||||
});
|
||||
|
||||
it("recovers when a showcase operation attempt hangs", async () => {
|
||||
let attempts = 0;
|
||||
const succeeded = await retryShowcaseOperation(
|
||||
() => {
|
||||
attempts += 1;
|
||||
return attempts === 1 ? new Promise<boolean>(() => undefined) : Promise.resolve(true);
|
||||
},
|
||||
{ isCancelled: () => false, attemptTimeoutMs: 1, retryDelayMs: 0 },
|
||||
);
|
||||
|
||||
assert.equal(succeeded, true);
|
||||
assert.equal(attempts, 2);
|
||||
});
|
||||
|
||||
it("stops retrying when the owning showcase effect is cancelled", async () => {
|
||||
let cancelled = false;
|
||||
const succeeded = await retryShowcaseOperation(
|
||||
async () => {
|
||||
cancelled = true;
|
||||
return false;
|
||||
},
|
||||
{ isCancelled: () => cancelled, retryDelayMs: 0 },
|
||||
);
|
||||
|
||||
assert.equal(succeeded, false);
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
export interface ShowcaseRetryOptions {
|
||||
readonly isCancelled: () => boolean;
|
||||
readonly attemptTimeoutMs?: number;
|
||||
readonly retryDelayMs?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_ATTEMPT_TIMEOUT_MS = 10_000;
|
||||
const DEFAULT_RETRY_DELAY_MS = 500;
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function runAttemptWithTimeout(
|
||||
operation: () => Promise<boolean>,
|
||||
timeoutMs: number,
|
||||
): Promise<boolean> {
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null;
|
||||
try {
|
||||
return await Promise.race([
|
||||
operation(),
|
||||
new Promise<boolean>((resolve) => {
|
||||
timeout = setTimeout(() => resolve(false), timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
if (timeout !== null) clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
/** Retry transient showcase setup work until it succeeds or the owning effect unmounts. */
|
||||
export async function retryShowcaseOperation(
|
||||
operation: () => Promise<boolean>,
|
||||
options: ShowcaseRetryOptions,
|
||||
): Promise<boolean> {
|
||||
const attemptTimeoutMs = options.attemptTimeoutMs ?? DEFAULT_ATTEMPT_TIMEOUT_MS;
|
||||
const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
|
||||
|
||||
while (!options.isCancelled()) {
|
||||
if (await runAttemptWithTimeout(operation, attemptTimeoutMs)) return true;
|
||||
if (!options.isCancelled()) await delay(retryDelayMs);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -37,6 +37,7 @@ interface TerminalSurfaceProps extends ViewProps {
|
||||
readonly buffer: string;
|
||||
readonly fontSize?: number;
|
||||
readonly isRunning: boolean;
|
||||
readonly autoFocus?: boolean;
|
||||
readonly keyboardFocusRequest?: number;
|
||||
readonly theme?: TerminalTheme;
|
||||
readonly onInput: (data: string) => void;
|
||||
@@ -145,7 +146,8 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
|
||||
onSubmitEditing={(event) => {
|
||||
const text = event.nativeEvent.text;
|
||||
if (text.length > 0) {
|
||||
props.onInput(`${text}\n`);
|
||||
// Terminal Enter is CR. LF is Ctrl+J and raw-mode TUIs can treat it as J.
|
||||
props.onInput(`${text}\r`);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@@ -214,6 +216,7 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf
|
||||
<View style={props.style}>
|
||||
<NativeTerminalSurfaceView
|
||||
appearanceScheme={appearanceScheme}
|
||||
autoFocus={props.autoFocus ?? true}
|
||||
backgroundColor={theme.background}
|
||||
focusRequest={props.isRunning ? (props.keyboardFocusRequest ?? 0) : 0}
|
||||
foregroundColor={theme.foreground}
|
||||
|
||||
@@ -70,6 +70,7 @@ import { cacheTerminalGridSize, getCachedTerminalGridSize } from "./terminalUiSt
|
||||
const DEFAULT_TERMINAL_COLS = 80;
|
||||
const DEFAULT_TERMINAL_ROWS = 24;
|
||||
const TERMINAL_ACCESSORY_HEIGHT = 52;
|
||||
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
|
||||
|
||||
type PendingModifier = "ctrl" | "meta";
|
||||
type HostPlatform = "mac" | "linux" | "windows" | "unknown";
|
||||
@@ -1218,6 +1219,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
|
||||
<>
|
||||
<View className="flex-1" style={{ paddingBottom: terminalBottomInset }}>
|
||||
<TerminalSurface
|
||||
autoFocus={!SHOWCASE_ENABLED}
|
||||
buffer={terminalSurfaceBuffer}
|
||||
fontSize={fontSize}
|
||||
isRunning={isRunning}
|
||||
|
||||
@@ -23,6 +23,7 @@ interface TerminalResizeEvent {
|
||||
|
||||
export interface NativeTerminalSurfaceProps extends ViewProps {
|
||||
readonly appearanceScheme?: "light" | "dark";
|
||||
readonly autoFocus?: boolean;
|
||||
readonly focusRequest?: number;
|
||||
readonly themeConfig?: string;
|
||||
readonly backgroundColor?: string;
|
||||
|
||||
@@ -9,6 +9,7 @@ type NewTaskDraftRouteParams = {
|
||||
readonly projectId?: string | string[];
|
||||
readonly title?: string | string[];
|
||||
readonly pendingTaskId?: string | string[];
|
||||
readonly incomingShareId?: string | string[];
|
||||
};
|
||||
|
||||
export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {
|
||||
@@ -36,6 +37,9 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
|
||||
/>
|
||||
<NewTaskDraftScreen
|
||||
initialProjectRef={initialProjectRef}
|
||||
incomingShareId={
|
||||
Array.isArray(params.incomingShareId) ? params.incomingShareId[0] : params.incomingShareId
|
||||
}
|
||||
pendingTaskId={
|
||||
Array.isArray(params.pendingTaskId) ? params.pendingTaskId[0] : params.pendingTaskId
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";
|
||||
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
|
||||
@@ -35,7 +35,13 @@ import {
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
|
||||
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
|
||||
import {
|
||||
clearComposerDraftContent,
|
||||
getComposerDraftSnapshot,
|
||||
mergeComposerDraftContent,
|
||||
restoreComposerDraftSnapshot,
|
||||
type ComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
@@ -43,6 +49,7 @@ import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../sta
|
||||
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
|
||||
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useCreateProjectThread } from "./use-project-actions";
|
||||
import { useIncomingShare } from "../sharing/IncomingShareProvider";
|
||||
|
||||
function formatWorkspaceLabel(input: {
|
||||
readonly workspaceMode: string;
|
||||
@@ -63,11 +70,20 @@ export function NewTaskDraftScreen(props: {
|
||||
};
|
||||
/** Queued outbox message id when editing an existing pending task. */
|
||||
readonly pendingTaskId?: string;
|
||||
/** Durable native share inbox item to merge into this project draft. */
|
||||
readonly incomingShareId?: string;
|
||||
}) {
|
||||
const projects = useProjects();
|
||||
const createProjectThread = useCreateProjectThread();
|
||||
const flow = useNewTaskFlow();
|
||||
const navigation = useNavigation();
|
||||
const {
|
||||
consumeShare,
|
||||
getShare,
|
||||
isLoading: isIncomingShareInboxLoading,
|
||||
releaseShareReservation,
|
||||
reserveShare,
|
||||
} = useIncomingShare();
|
||||
const insets = useSafeAreaInsets();
|
||||
const colorScheme = useColorScheme();
|
||||
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
|
||||
@@ -82,10 +98,94 @@ export function NewTaskDraftScreen(props: {
|
||||
const promptInputRef = useRef<ComposerEditorHandle>(null);
|
||||
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
|
||||
const [isComposerFocused, setIsComposerFocused] = useState(false);
|
||||
const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
|
||||
const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
|
||||
const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
|
||||
const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);
|
||||
const [shareImportAttempt, setShareImportAttempt] = useState(0);
|
||||
const startedShareImportKeyRef = useRef<string | null>(null);
|
||||
const cancellingShareImportKeyRef = useRef<string | null>(null);
|
||||
const shareImportDraftBackupRef = useRef(new Map<string, ComposerDraft>());
|
||||
const activeShareImportTokenRef = useRef<symbol | null>(null);
|
||||
const shareImportMountedRef = useRef(true);
|
||||
const latestDraftKeyRef = useRef(flow.draftKey);
|
||||
const latestIncomingShareIdRef = useRef(props.incomingShareId);
|
||||
latestDraftKeyRef.current = flow.draftKey;
|
||||
latestIncomingShareIdRef.current = props.incomingShareId;
|
||||
const isImportingShare = importingShareKey !== null;
|
||||
const alertedUnavailableIncomingShareIdRef = useRef<string | null>(null);
|
||||
const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null;
|
||||
const requestedInitialProjectAvailable = Boolean(
|
||||
props.initialProjectRef?.environmentId &&
|
||||
props.initialProjectRef.projectId &&
|
||||
projects.some(
|
||||
(project) =>
|
||||
project.environmentId === props.initialProjectRef?.environmentId &&
|
||||
project.id === props.initialProjectRef?.projectId,
|
||||
),
|
||||
);
|
||||
const isProjectPickerReturnActive =
|
||||
isReturningToProjectPicker && !requestedInitialProjectAvailable;
|
||||
const isIncomingShareTransferPending = Boolean(
|
||||
incomingShare && cancelledIncomingShareId !== props.incomingShareId,
|
||||
);
|
||||
usePreventRemove(
|
||||
(isIncomingShareTransferPending && !isProjectPickerReturnActive) || isCancellingShareImport,
|
||||
() => undefined,
|
||||
);
|
||||
const hasImportedIncomingShare = Boolean(
|
||||
props.incomingShareId &&
|
||||
flow.draftKey &&
|
||||
getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId),
|
||||
);
|
||||
const isIncomingShareUnavailable = Boolean(
|
||||
props.incomingShareId &&
|
||||
!isIncomingShareInboxLoading &&
|
||||
!incomingShare &&
|
||||
!hasImportedIncomingShare,
|
||||
);
|
||||
const isIncomingShareReady =
|
||||
!props.incomingShareId ||
|
||||
(hasImportedIncomingShare && !incomingShare) ||
|
||||
isIncomingShareUnavailable;
|
||||
const appliedInitialProjectKeyRef = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (cancelledIncomingShareId === props.incomingShareId) {
|
||||
navigation.goBack();
|
||||
}
|
||||
}, [cancelledIncomingShareId, navigation, props.incomingShareId]);
|
||||
useEffect(() => {
|
||||
if (!isReturningToProjectPicker) {
|
||||
return;
|
||||
}
|
||||
if (requestedInitialProjectAvailable) {
|
||||
setIsReturningToProjectPicker(false);
|
||||
return;
|
||||
}
|
||||
// Let usePreventRemove commit its disabled state before replacing this
|
||||
// route, otherwise the transfer guard can swallow the fallback action.
|
||||
const frame = requestAnimationFrame(() => {
|
||||
navigation.dispatch(
|
||||
StackActions.replace("NewTask", { incomingShareId: props.incomingShareId }),
|
||||
);
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [
|
||||
isReturningToProjectPicker,
|
||||
navigation,
|
||||
props.incomingShareId,
|
||||
requestedInitialProjectAvailable,
|
||||
]);
|
||||
useEffect(() => {
|
||||
if (!shareImportMountedRef.current) {
|
||||
startedShareImportKeyRef.current = null;
|
||||
}
|
||||
shareImportMountedRef.current = true;
|
||||
return () => {
|
||||
appliedInitialProjectKeyRef.current = null;
|
||||
shareImportMountedRef.current = false;
|
||||
activeShareImportTokenRef.current = null;
|
||||
cancellingShareImportKeyRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -163,6 +263,14 @@ export function NewTaskDraftScreen(props: {
|
||||
setProject(directProject);
|
||||
return;
|
||||
}
|
||||
|
||||
if (projects.length > 0) {
|
||||
// Never fall through to the flow provider's temporary first-project
|
||||
// default. Return to the picker with the share id intact so the user
|
||||
// can choose an available destination.
|
||||
setIsReturningToProjectPicker(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedProject) {
|
||||
@@ -179,6 +287,7 @@ export function NewTaskDraftScreen(props: {
|
||||
logicalProjects,
|
||||
projects,
|
||||
props.initialProjectRef,
|
||||
props.incomingShareId,
|
||||
props.pendingTaskId,
|
||||
navigation,
|
||||
selectedProject,
|
||||
@@ -198,6 +307,205 @@ export function NewTaskDraftScreen(props: {
|
||||
void flow.loadBranches();
|
||||
}, [flow.loadBranches, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
const shareId = props.incomingShareId;
|
||||
const draftKey = flow.draftKey;
|
||||
const destinationProject = selectedProject;
|
||||
const initialEnvironmentId = props.initialProjectRef?.environmentId;
|
||||
const initialProjectId = props.initialProjectRef?.projectId;
|
||||
const selectedProjectMatchesRoute =
|
||||
!initialEnvironmentId ||
|
||||
!initialProjectId ||
|
||||
(destinationProject?.environmentId === initialEnvironmentId &&
|
||||
destinationProject.id === initialProjectId);
|
||||
if (
|
||||
!shareId ||
|
||||
!draftKey ||
|
||||
!destinationProject ||
|
||||
!selectedProjectMatchesRoute ||
|
||||
cancelledIncomingShareId === shareId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const importKey = `${shareId}:${draftKey}`;
|
||||
if (
|
||||
startedShareImportKeyRef.current === importKey ||
|
||||
cancellingShareImportKeyRef.current === importKey
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!incomingShare) {
|
||||
if (isIncomingShareUnavailable && alertedUnavailableIncomingShareIdRef.current !== shareId) {
|
||||
alertedUnavailableIncomingShareIdRef.current = shareId;
|
||||
Alert.alert(
|
||||
"Shared content unavailable",
|
||||
"The shared content is no longer in the inbox. You can continue editing this task draft.",
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (alertedUnavailableIncomingShareIdRef.current === shareId) {
|
||||
alertedUnavailableIncomingShareIdRef.current = null;
|
||||
}
|
||||
startedShareImportKeyRef.current = importKey;
|
||||
const draftBackup =
|
||||
shareImportDraftBackupRef.current.get(importKey) ?? getComposerDraftSnapshot(draftKey);
|
||||
shareImportDraftBackupRef.current.set(importKey, draftBackup);
|
||||
const importToken = Symbol(importKey);
|
||||
let didReserveShare = false;
|
||||
let needsDraftRestore = false;
|
||||
activeShareImportTokenRef.current = importToken;
|
||||
setImportingShareKey(importKey);
|
||||
void (async () => {
|
||||
await reserveShare(shareId, {
|
||||
environmentId: String(destinationProject.environmentId),
|
||||
projectId: String(destinationProject.id),
|
||||
});
|
||||
didReserveShare = true;
|
||||
if (
|
||||
!shareImportMountedRef.current ||
|
||||
activeShareImportTokenRef.current !== importToken ||
|
||||
latestDraftKeyRef.current !== draftKey ||
|
||||
latestIncomingShareIdRef.current !== shareId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
needsDraftRestore = true;
|
||||
const { skippedAttachmentCount } = await mergeComposerDraftContent(draftKey, {
|
||||
text: incomingShare.text,
|
||||
attachments: incomingShare.attachments,
|
||||
sourceShareId: shareId,
|
||||
});
|
||||
if (
|
||||
!shareImportMountedRef.current ||
|
||||
activeShareImportTokenRef.current !== importToken ||
|
||||
latestDraftKeyRef.current !== draftKey ||
|
||||
latestIncomingShareIdRef.current !== shareId
|
||||
) {
|
||||
// The durable reservation makes an interrupted transfer resume only
|
||||
// in this project instead of copying into a second project draft.
|
||||
return;
|
||||
}
|
||||
await consumeShare(shareId);
|
||||
if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
|
||||
return;
|
||||
}
|
||||
const warnings = [...incomingShare.warnings];
|
||||
if (skippedAttachmentCount > 0) {
|
||||
warnings.push(
|
||||
`${skippedAttachmentCount} shared image${skippedAttachmentCount === 1 ? " was" : "s were"} skipped because this draft reached the attachment limit.`,
|
||||
);
|
||||
}
|
||||
if (warnings.length > 0) {
|
||||
Alert.alert("Some shared content was skipped", warnings.join("\n"));
|
||||
}
|
||||
shareImportDraftBackupRef.current.delete(importKey);
|
||||
})()
|
||||
.catch((error) => {
|
||||
if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
|
||||
return;
|
||||
}
|
||||
Alert.alert(
|
||||
"Could not import shared content",
|
||||
error instanceof Error ? error.message : "The shared content could not be saved.",
|
||||
[
|
||||
{
|
||||
text: "Cancel import",
|
||||
style: "cancel",
|
||||
onPress: () => {
|
||||
const cancelImport = async (): Promise<void> => {
|
||||
if (!shareImportMountedRef.current) {
|
||||
return;
|
||||
}
|
||||
// Latch synchronously before restoring the draft. The
|
||||
// restore publishes atom state and can re-run the import
|
||||
// effect before React commits the cancelling state update.
|
||||
cancellingShareImportKeyRef.current = importKey;
|
||||
setIsCancellingShareImport(true);
|
||||
try {
|
||||
if (needsDraftRestore) {
|
||||
await restoreComposerDraftSnapshot(draftKey, draftBackup);
|
||||
needsDraftRestore = false;
|
||||
}
|
||||
if (didReserveShare) {
|
||||
await releaseShareReservation(shareId, {
|
||||
environmentId: String(destinationProject.environmentId),
|
||||
projectId: String(destinationProject.id),
|
||||
});
|
||||
}
|
||||
shareImportDraftBackupRef.current.delete(importKey);
|
||||
if (shareImportMountedRef.current) {
|
||||
setIsCancellingShareImport(false);
|
||||
setCancelledIncomingShareId(shareId);
|
||||
}
|
||||
} catch (cancelError) {
|
||||
if (!shareImportMountedRef.current) {
|
||||
return;
|
||||
}
|
||||
Alert.alert(
|
||||
"Could not cancel import",
|
||||
cancelError instanceof Error
|
||||
? cancelError.message
|
||||
: "The shared content could not be restored safely.",
|
||||
[
|
||||
{
|
||||
text: "Retry import",
|
||||
onPress: () => {
|
||||
cancellingShareImportKeyRef.current = null;
|
||||
setIsCancellingShareImport(false);
|
||||
setShareImportAttempt((attempt) => attempt + 1);
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Retry cancel",
|
||||
onPress: () => void cancelImport(),
|
||||
},
|
||||
],
|
||||
{ cancelable: false },
|
||||
);
|
||||
}
|
||||
};
|
||||
void cancelImport();
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Retry",
|
||||
onPress: () => setShareImportAttempt((attempt) => attempt + 1),
|
||||
},
|
||||
],
|
||||
{ cancelable: false },
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
if (startedShareImportKeyRef.current === importKey) {
|
||||
// Every terminal path, including an invalidated operation, must
|
||||
// release the synchronous start latch so this transfer can retry.
|
||||
startedShareImportKeyRef.current = null;
|
||||
}
|
||||
if (shareImportMountedRef.current && activeShareImportTokenRef.current === importToken) {
|
||||
activeShareImportTokenRef.current = null;
|
||||
setImportingShareKey(null);
|
||||
}
|
||||
});
|
||||
}, [
|
||||
consumeShare,
|
||||
cancelledIncomingShareId,
|
||||
flow.draftKey,
|
||||
hasImportedIncomingShare,
|
||||
incomingShare,
|
||||
isIncomingShareInboxLoading,
|
||||
isIncomingShareUnavailable,
|
||||
props.incomingShareId,
|
||||
props.initialProjectRef?.environmentId,
|
||||
props.initialProjectRef?.projectId,
|
||||
releaseShareReservation,
|
||||
reserveShare,
|
||||
selectedProject,
|
||||
shareImportAttempt,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
// Android starts with the collapsed composer pill (like an open thread)
|
||||
// and only expands/focuses when tapped.
|
||||
@@ -223,10 +531,11 @@ export function NewTaskDraftScreen(props: {
|
||||
flow.environments.map((environment) => ({
|
||||
id: `environment:${environment.environmentId}`,
|
||||
title: environment.environmentLabel,
|
||||
attributes: isIncomingShareTransferPending ? { disabled: true } : undefined,
|
||||
state:
|
||||
flow.selectedEnvironmentId === environment.environmentId ? ("on" as const) : undefined,
|
||||
})),
|
||||
[flow.environments, flow.selectedEnvironmentId],
|
||||
[flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],
|
||||
);
|
||||
|
||||
const modelMenuActions = useMemo(
|
||||
@@ -391,20 +700,23 @@ export function NewTaskDraftScreen(props: {
|
||||
[currentBranchName, flow.selectedBranchName, flow.workspaceMode],
|
||||
);
|
||||
function handleModelMenuAction(event: string) {
|
||||
if (!event.startsWith("model:")) {
|
||||
if (isIncomingShareTransferPending || !event.startsWith("model:")) {
|
||||
return;
|
||||
}
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
}
|
||||
|
||||
function handleEnvironmentMenuAction(event: string) {
|
||||
if (!event.startsWith("environment:")) {
|
||||
if (isIncomingShareTransferPending || !event.startsWith("environment:")) {
|
||||
return;
|
||||
}
|
||||
flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
|
||||
}
|
||||
|
||||
function handleOptionsMenuAction(event: string) {
|
||||
if (isIncomingShareTransferPending) {
|
||||
return;
|
||||
}
|
||||
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
|
||||
if (providerOptions) {
|
||||
flow.setSelectedModelOptions(providerOptions);
|
||||
@@ -424,6 +736,9 @@ export function NewTaskDraftScreen(props: {
|
||||
}
|
||||
|
||||
function handleWorkspaceMenuAction(event: string) {
|
||||
if (isIncomingShareTransferPending) {
|
||||
return;
|
||||
}
|
||||
if (event.startsWith("workspace:mode:")) {
|
||||
flow.setWorkspaceMode(
|
||||
event.slice("workspace:mode:".length) as Parameters<typeof flow.setWorkspaceMode>[0],
|
||||
@@ -444,6 +759,9 @@ export function NewTaskDraftScreen(props: {
|
||||
}
|
||||
|
||||
async function handlePickImages(): Promise<void> {
|
||||
if (isIncomingShareTransferPending) {
|
||||
return;
|
||||
}
|
||||
const result = await pickComposerImages({ existingCount: flow.attachments.length });
|
||||
if (result.images.length > 0) {
|
||||
flow.appendAttachments(result.images);
|
||||
@@ -526,8 +844,7 @@ export function NewTaskDraftScreen(props: {
|
||||
if (editingPendingTask) {
|
||||
flow.finishEditingPendingTask();
|
||||
} else {
|
||||
flow.setPrompt("");
|
||||
flow.clearAttachments();
|
||||
clearComposerDraftContent(draftKey);
|
||||
}
|
||||
navigation.getParent()?.goBack();
|
||||
return;
|
||||
@@ -585,8 +902,7 @@ export function NewTaskDraftScreen(props: {
|
||||
}
|
||||
flow.finishEditingPendingTask();
|
||||
} else {
|
||||
flow.setPrompt("");
|
||||
flow.clearAttachments();
|
||||
clearComposerDraftContent(draftKey);
|
||||
}
|
||||
navigation.dispatch(
|
||||
StackActions.replace("Thread", {
|
||||
@@ -620,12 +936,15 @@ export function NewTaskDraftScreen(props: {
|
||||
Boolean(flow.selectedProject) &&
|
||||
Boolean(flow.selectedModel) &&
|
||||
flow.prompt.trim().length > 0 &&
|
||||
isIncomingShareReady &&
|
||||
!isImportingShare &&
|
||||
!flow.submitting &&
|
||||
!(flow.workspaceMode === "worktree" && !flow.selectedBranchName);
|
||||
const promptEditor = (
|
||||
<ComposerEditor
|
||||
ref={promptInputRef}
|
||||
autoFocus={!isAndroid}
|
||||
editable={!isIncomingShareTransferPending}
|
||||
multiline
|
||||
scrollEnabled={isExpanded}
|
||||
value={flow.prompt}
|
||||
@@ -660,6 +979,7 @@ export function NewTaskDraftScreen(props: {
|
||||
icon="plus"
|
||||
onPress={() => void handlePickImages()}
|
||||
showChevron={false}
|
||||
disabled={isIncomingShareTransferPending}
|
||||
/>
|
||||
<ControlPillMenu
|
||||
actions={modelMenuActions}
|
||||
@@ -667,6 +987,7 @@ export function NewTaskDraftScreen(props: {
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Model"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
|
||||
label={flow.selectedModelOption?.label ?? "Model"}
|
||||
/>
|
||||
@@ -677,6 +998,7 @@ export function NewTaskDraftScreen(props: {
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Configuration"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="slider.horizontal.3"
|
||||
label={configurationLabel}
|
||||
/>
|
||||
@@ -687,6 +1009,7 @@ export function NewTaskDraftScreen(props: {
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Environment"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="desktopcomputer"
|
||||
label={selectedEnvironmentLabel}
|
||||
/>
|
||||
@@ -697,6 +1020,7 @@ export function NewTaskDraftScreen(props: {
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Workspace"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="point.topleft.down.curvedto.point.bottomright.up"
|
||||
label={workspaceLabel}
|
||||
/>
|
||||
@@ -763,7 +1087,9 @@ export function NewTaskDraftScreen(props: {
|
||||
<View className="pb-2.5">
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
onRemove={flow.removeAttachment}
|
||||
onRemove={
|
||||
isIncomingShareTransferPending ? () => undefined : flow.removeAttachment
|
||||
}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
@@ -807,7 +1133,7 @@ export function NewTaskDraftScreen(props: {
|
||||
<View className="px-4 pt-3">
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
onRemove={flow.removeAttachment}
|
||||
onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
|
||||
imageSize={88}
|
||||
imageBorderRadius={20}
|
||||
/>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { useMemo } from "react";
|
||||
import { ActivityIndicator, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { cn } from "../../lib/cn";
|
||||
@@ -16,6 +16,11 @@ import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { useIncomingShare } from "../sharing/IncomingShareProvider";
|
||||
|
||||
type NewTaskRouteParams = {
|
||||
readonly incomingShareId?: string | string[];
|
||||
};
|
||||
|
||||
function deriveProjectEmptyState(catalogState: WorkspaceState): {
|
||||
readonly title: string;
|
||||
@@ -72,15 +77,29 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
|
||||
};
|
||||
}
|
||||
|
||||
export function NewTaskRouteScreen() {
|
||||
export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { state: catalogState } = useWorkspaceState();
|
||||
const navigation = useNavigation();
|
||||
const isFocused = useIsFocused();
|
||||
const { layout } = useAdaptiveWorkspaceLayout();
|
||||
const insets = useSafeAreaInsets();
|
||||
const chevronColor = useThemeColor("--color-chevron");
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
const { getShare, releaseShareReservation } = useIncomingShare();
|
||||
const routeShareId = Array.isArray(route.params?.incomingShareId)
|
||||
? route.params.incomingShareId[0]
|
||||
: route.params?.incomingShareId;
|
||||
const incomingShare = routeShareId ? getShare(routeShareId) : null;
|
||||
const incomingShareSubtitle = incomingShare
|
||||
? incomingShare.attachments.length === 0
|
||||
? "Choose a project for what you shared"
|
||||
: incomingShare.attachments.length === 1
|
||||
? "Choose a project for the image you shared"
|
||||
: `Choose a project for the ${incomingShare.attachments.length} images you shared`
|
||||
: null;
|
||||
const screenTitle = incomingShare ? "Start a task" : "Choose project";
|
||||
const repositoryGroups = useMemo(
|
||||
() => groupProjectsByRepository({ projects, threads }),
|
||||
[projects, threads],
|
||||
@@ -109,6 +128,70 @@ export function NewTaskRouteScreen() {
|
||||
return nextItems;
|
||||
}, [repositoryGroups]);
|
||||
const projectEmptyState = deriveProjectEmptyState(catalogState);
|
||||
const resumedDestinationKeyRef = useRef<string | null>(null);
|
||||
const reservedDestinationProject = incomingShare?.destination
|
||||
? (projects.find(
|
||||
(project) =>
|
||||
project.environmentId === incomingShare.destination?.environmentId &&
|
||||
project.id === incomingShare.destination?.projectId,
|
||||
) ?? null)
|
||||
: null;
|
||||
|
||||
async function selectProject(item: (typeof items)[number]): Promise<void> {
|
||||
if (incomingShare?.destination && !reservedDestinationProject) {
|
||||
try {
|
||||
await releaseShareReservation(incomingShare.id, incomingShare.destination);
|
||||
} catch (error) {
|
||||
Alert.alert(
|
||||
"Could not change project",
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "The shared content reservation could not be updated.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: item.environmentId,
|
||||
projectId: item.id,
|
||||
title: item.title,
|
||||
incomingShareId: incomingShare?.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const destination = incomingShare?.destination;
|
||||
if (!destination) {
|
||||
resumedDestinationKeyRef.current = null;
|
||||
return;
|
||||
}
|
||||
if (!isFocused) {
|
||||
// Returning from the reserved draft is a fresh resume attempt. Keeping
|
||||
// this latch set would leave every project row disabled with no route.
|
||||
resumedDestinationKeyRef.current = null;
|
||||
return;
|
||||
}
|
||||
const destinationKey = `${incomingShare.id}:${destination.environmentId}:${destination.projectId}`;
|
||||
if (resumedDestinationKeyRef.current === destinationKey) {
|
||||
return;
|
||||
}
|
||||
if (!reservedDestinationProject) {
|
||||
return;
|
||||
}
|
||||
resumedDestinationKeyRef.current = destinationKey;
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: reservedDestinationProject.environmentId,
|
||||
projectId: reservedDestinationProject.id,
|
||||
title: reservedDestinationProject.title,
|
||||
incomingShareId: incomingShare.id,
|
||||
},
|
||||
});
|
||||
}, [incomingShare, isFocused, navigation, reservedDestinationProject]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
@@ -117,7 +200,8 @@ export function NewTaskRouteScreen() {
|
||||
{/* Android renders its own in-screen header instead of the native bar. */}
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader
|
||||
title="Choose project"
|
||||
title={screenTitle}
|
||||
subtitle={incomingShareSubtitle}
|
||||
onBack={layout.usesSplitView ? () => navigation.goBack() : undefined}
|
||||
actions={[
|
||||
{
|
||||
@@ -129,21 +213,29 @@ export function NewTaskRouteScreen() {
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<NativeHeaderToolbar placement="right">
|
||||
{layout.usesSplitView ? (
|
||||
<>
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
title: screenTitle,
|
||||
unstable_headerSubtitle: incomingShareSubtitle ?? undefined,
|
||||
}}
|
||||
/>
|
||||
<NativeHeaderToolbar placement="right">
|
||||
{layout.usesSplitView ? (
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="Close new task"
|
||||
icon="xmark"
|
||||
onPress={() => navigation.goBack()}
|
||||
separateBackground
|
||||
/>
|
||||
) : null}
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="Close new task"
|
||||
icon="xmark"
|
||||
onPress={() => navigation.goBack()}
|
||||
icon="plus"
|
||||
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
|
||||
separateBackground
|
||||
/>
|
||||
) : null}
|
||||
<NativeHeaderToolbar.Button
|
||||
icon="plus"
|
||||
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
|
||||
separateBackground
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
</NativeHeaderToolbar>
|
||||
</>
|
||||
)}
|
||||
|
||||
<ScrollView
|
||||
@@ -152,6 +244,7 @@ export function NewTaskRouteScreen() {
|
||||
className="flex-1"
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
gap: 12,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 8,
|
||||
}}
|
||||
@@ -194,16 +287,8 @@ export function NewTaskRouteScreen() {
|
||||
return (
|
||||
<Pressable
|
||||
key={item.key}
|
||||
onPress={() =>
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: item.environmentId,
|
||||
projectId: item.id,
|
||||
title: item.title,
|
||||
},
|
||||
})
|
||||
}
|
||||
disabled={reservedDestinationProject !== null}
|
||||
onPress={() => void selectProject(item)}
|
||||
className={cn(
|
||||
"bg-card px-4 py-3.5",
|
||||
!isFirst && "border-t border-border-subtle",
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { useState } from "react";
|
||||
import { Pressable, ScrollView, View } from "react-native";
|
||||
import { Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
|
||||
import { cn } from "../../../lib/cn";
|
||||
import { useEnvironmentQuery } from "../../../state/query";
|
||||
@@ -57,115 +58,125 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) {
|
||||
const disabledExistingBranches = new Set(disabledExistingBranchNames);
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerClassName="gap-4 px-5 pt-2"
|
||||
>
|
||||
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
New branch
|
||||
</Text>
|
||||
<TextInput
|
||||
value={newBranchName}
|
||||
onChangeText={setNewBranchName}
|
||||
placeholder="feature/mobile-polish"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<SheetActionButton
|
||||
icon="plus"
|
||||
label="Create & checkout"
|
||||
tone="primary"
|
||||
disabled={busy || newBranchName.trim().length === 0}
|
||||
onPress={() => {
|
||||
const branch = sanitizeFeatureBranchName(newBranchName.trim());
|
||||
if (branch.length === 0) return;
|
||||
void gitActions.onCreateSelectedThreadBranch(branch).then(() => {
|
||||
setNewBranchName("");
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
New worktree
|
||||
</Text>
|
||||
<TextInput
|
||||
value={worktreeBaseBranch}
|
||||
onChangeText={setWorktreeBaseBranch}
|
||||
placeholder="main"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<TextInput
|
||||
value={worktreeBranchName}
|
||||
onChangeText={setWorktreeBranchName}
|
||||
placeholder="feature/mobile-thread"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<SheetActionButton
|
||||
icon="square.split.2x1"
|
||||
label="Create worktree"
|
||||
tone="primary"
|
||||
disabled={
|
||||
busy || worktreeBaseBranch.trim().length === 0 || worktreeBranchName.trim().length === 0
|
||||
}
|
||||
onPress={() => {
|
||||
const baseBranch = worktreeBaseBranch.trim();
|
||||
const newBranch = worktreeBranchName.trim();
|
||||
if (baseBranch.length === 0 || newBranch.length === 0) return;
|
||||
void gitActions.onCreateSelectedThreadWorktree({ baseBranch, newBranch }).then(() => {
|
||||
setWorktreeBranchName("");
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="gap-2">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
Existing branches
|
||||
</Text>
|
||||
{branchesLoading ? (
|
||||
<Text className="text-foreground-secondary text-sm font-medium">Loading branches...</Text>
|
||||
) : null}
|
||||
{!branchesLoading && availableBranches.length === 0 ? (
|
||||
<Text className="text-foreground-secondary text-sm font-medium">
|
||||
No local branches found.
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<AndroidSheetHeader title="Branches & worktrees" onBack={() => navigation.goBack()} />
|
||||
) : null}
|
||||
<ScrollView
|
||||
className="flex-1"
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerClassName="gap-4 px-5 pt-2"
|
||||
>
|
||||
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
New branch
|
||||
</Text>
|
||||
) : null}
|
||||
{availableBranches.map((branch) => {
|
||||
const disabled = disabledExistingBranches.has(branch.name);
|
||||
const subtitle = branch.worktreePath
|
||||
? branch.worktreePath === currentWorktreePath
|
||||
? "Checked out in this thread"
|
||||
: "Checked out in another worktree"
|
||||
: branch.isDefault
|
||||
? "Default branch"
|
||||
: "Local branch";
|
||||
<TextInput
|
||||
value={newBranchName}
|
||||
onChangeText={setNewBranchName}
|
||||
placeholder="feature/mobile-polish"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<SheetActionButton
|
||||
icon="plus"
|
||||
label="Create & checkout"
|
||||
tone="primary"
|
||||
disabled={busy || newBranchName.trim().length === 0}
|
||||
onPress={() => {
|
||||
const branch = sanitizeFeatureBranchName(newBranchName.trim());
|
||||
if (branch.length === 0) return;
|
||||
void gitActions.onCreateSelectedThreadBranch(branch).then(() => {
|
||||
setNewBranchName("");
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
key={branch.name}
|
||||
className={cn(
|
||||
"gap-1 rounded-[18px] border px-4 py-3 disabled:opacity-[0.45]",
|
||||
branch.current ? "border-subtle-strong" : "border-border",
|
||||
)}
|
||||
disabled={busy || disabled}
|
||||
onPress={() => {
|
||||
void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => {
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
>
|
||||
<View className="absolute inset-0 rounded-[18px] bg-card" />
|
||||
<Text className="text-foreground text-base font-t3-bold">{branch.name}</Text>
|
||||
<Text className="text-foreground-secondary text-xs font-medium">{subtitle}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</ScrollView>
|
||||
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
New worktree
|
||||
</Text>
|
||||
<TextInput
|
||||
value={worktreeBaseBranch}
|
||||
onChangeText={setWorktreeBaseBranch}
|
||||
placeholder="main"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<TextInput
|
||||
value={worktreeBranchName}
|
||||
onChangeText={setWorktreeBranchName}
|
||||
placeholder="feature/mobile-thread"
|
||||
className="rounded-[18px]"
|
||||
/>
|
||||
<SheetActionButton
|
||||
icon="square.split.2x1"
|
||||
label="Create worktree"
|
||||
tone="primary"
|
||||
disabled={
|
||||
busy ||
|
||||
worktreeBaseBranch.trim().length === 0 ||
|
||||
worktreeBranchName.trim().length === 0
|
||||
}
|
||||
onPress={() => {
|
||||
const baseBranch = worktreeBaseBranch.trim();
|
||||
const newBranch = worktreeBranchName.trim();
|
||||
if (baseBranch.length === 0 || newBranch.length === 0) return;
|
||||
void gitActions.onCreateSelectedThreadWorktree({ baseBranch, newBranch }).then(() => {
|
||||
setWorktreeBranchName("");
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="gap-2">
|
||||
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
|
||||
Existing branches
|
||||
</Text>
|
||||
{branchesLoading ? (
|
||||
<Text className="text-foreground-secondary text-sm font-medium">
|
||||
Loading branches...
|
||||
</Text>
|
||||
) : null}
|
||||
{!branchesLoading && availableBranches.length === 0 ? (
|
||||
<Text className="text-foreground-secondary text-sm font-medium">
|
||||
No local branches found.
|
||||
</Text>
|
||||
) : null}
|
||||
{availableBranches.map((branch) => {
|
||||
const disabled = disabledExistingBranches.has(branch.name);
|
||||
const subtitle = branch.worktreePath
|
||||
? branch.worktreePath === currentWorktreePath
|
||||
? "Checked out in this thread"
|
||||
: "Checked out in another worktree"
|
||||
: branch.isDefault
|
||||
? "Default branch"
|
||||
: "Local branch";
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
key={branch.name}
|
||||
className={cn(
|
||||
"gap-1 rounded-[18px] border px-4 py-3 disabled:opacity-[0.45]",
|
||||
branch.current ? "border-subtle-strong" : "border-border",
|
||||
)}
|
||||
disabled={busy || disabled}
|
||||
onPress={() => {
|
||||
void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => {
|
||||
navigation.goBack();
|
||||
});
|
||||
}}
|
||||
>
|
||||
<View className="absolute inset-0 rounded-[18px] bg-card" />
|
||||
<Text className="text-foreground text-base font-t3-bold">{branch.name}</Text>
|
||||
<Text className="text-foreground-secondary text-xs font-medium">{subtitle}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { useCallback, useState } from "react";
|
||||
import { Pressable, ScrollView, View } from "react-native";
|
||||
import { Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
|
||||
import { cn } from "../../../lib/cn";
|
||||
import { useEnvironmentQuery } from "../../../state/query";
|
||||
@@ -65,160 +66,168 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
|
||||
);
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerClassName="gap-4 px-5 pt-2"
|
||||
>
|
||||
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<Text className="text-foreground-muted text-sm font-medium">Branch</Text>
|
||||
<Text className="text-foreground text-base font-t3-bold">
|
||||
{gitStatus.data?.refName ?? "(detached HEAD)"}
|
||||
</Text>
|
||||
</View>
|
||||
{isDefaultRef ? (
|
||||
<Text className="text-xs leading-normal text-amber-700 dark:text-amber-400">
|
||||
Warning: this is the default branch.
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<View className="gap-1">
|
||||
<Text className="text-foreground text-base font-t3-bold">Files</Text>
|
||||
<Text className="text-foreground-muted text-xs leading-normal">
|
||||
{selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions}
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<AndroidSheetHeader title="Commit changes" onBack={() => navigation.goBack()} />
|
||||
) : null}
|
||||
<ScrollView
|
||||
className="flex-1"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerClassName="gap-4 px-5 pt-2"
|
||||
>
|
||||
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<Text className="text-foreground-muted text-sm font-medium">Branch</Text>
|
||||
<Text className="text-foreground text-base font-t3-bold">
|
||||
{gitStatus.data?.refName ?? "(detached HEAD)"}
|
||||
</Text>
|
||||
</View>
|
||||
<View className="flex-row items-center gap-2">
|
||||
{!allSelected && isEditingFiles ? (
|
||||
{isDefaultRef ? (
|
||||
<Text className="text-xs leading-normal text-amber-700 dark:text-amber-400">
|
||||
Warning: this is the default branch.
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<View className="gap-3 rounded-[22px] border border-border bg-card px-4 py-4">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<View className="gap-1">
|
||||
<Text className="text-foreground text-base font-t3-bold">Files</Text>
|
||||
<Text className="text-foreground-muted text-xs leading-normal">
|
||||
{selectedFiles.length} selected · +{selectedInsertions} / -{selectedDeletions}
|
||||
</Text>
|
||||
</View>
|
||||
<View className="flex-row items-center gap-2">
|
||||
{!allSelected && isEditingFiles ? (
|
||||
<Pressable
|
||||
className="bg-subtle rounded-full px-3 py-2"
|
||||
onPress={() => setExcludedFiles(new Set())}
|
||||
>
|
||||
<Text className="text-foreground text-2xs font-t3-bold uppercase">Reset</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
<Pressable
|
||||
className="bg-subtle rounded-full px-3 py-2"
|
||||
onPress={() => setExcludedFiles(new Set())}
|
||||
onPress={() => setIsEditingFiles((current) => !current)}
|
||||
>
|
||||
<Text className="text-foreground text-2xs font-t3-bold uppercase">Reset</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
<Pressable
|
||||
className="bg-subtle rounded-full px-3 py-2"
|
||||
onPress={() => setIsEditingFiles((current) => !current)}
|
||||
>
|
||||
<Text className="text-foreground text-2xs font-t3-bold uppercase">
|
||||
{isEditingFiles ? "Done" : "Edit"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{allFiles.length === 0 ? (
|
||||
<Text className="text-foreground-secondary text-sm leading-normal">
|
||||
No changed files are available to commit.
|
||||
</Text>
|
||||
) : !isEditingFiles ? (
|
||||
<View className="gap-2">
|
||||
{selectedFilePreview.map((file) => (
|
||||
<View key={file.path} className="flex-row items-center justify-between gap-3">
|
||||
<Text className="text-foreground flex-1 text-sm font-medium" numberOfLines={1}>
|
||||
{file.path}
|
||||
<Text className="text-foreground text-2xs font-t3-bold uppercase">
|
||||
{isEditingFiles ? "Done" : "Edit"}
|
||||
</Text>
|
||||
<Text className="text-xs font-t3-bold text-emerald-500">+{file.insertions}</Text>
|
||||
<Text className="text-xs font-t3-bold text-rose-500">-{file.deletions}</Text>
|
||||
</View>
|
||||
))}
|
||||
{selectedFiles.length > selectedFilePreview.length ? (
|
||||
<Text className="text-foreground-muted text-xs leading-snug">
|
||||
+{selectedFiles.length - selectedFilePreview.length} more files
|
||||
</Text>
|
||||
) : null}
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
<View className="gap-2">
|
||||
{allFiles.map((file) => {
|
||||
const included = !excludedFiles.has(file.path);
|
||||
return (
|
||||
<Pressable
|
||||
key={file.path}
|
||||
className={cn(
|
||||
"rounded-[18px] border px-4 py-3",
|
||||
included ? "border-border" : "border-border-subtle",
|
||||
)}
|
||||
onPress={() => {
|
||||
setExcludedFiles((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(file.path)) {
|
||||
next.delete(file.path);
|
||||
} else {
|
||||
next.add(file.path);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
>
|
||||
<View
|
||||
className={`absolute inset-0 rounded-[18px] ${included ? "bg-card" : "bg-subtle"}`}
|
||||
/>
|
||||
<View className="flex-row items-start justify-between gap-3">
|
||||
<View className="flex-1 gap-1">
|
||||
<Text
|
||||
selectable
|
||||
className={`text-sm font-t3-bold ${included ? "text-foreground" : "text-foreground-muted"}`}
|
||||
>
|
||||
{file.path}
|
||||
</Text>
|
||||
{!included ? (
|
||||
<Text className="text-foreground-muted text-2xs leading-normal">
|
||||
Excluded from this commit
|
||||
|
||||
{allFiles.length === 0 ? (
|
||||
<Text className="text-foreground-secondary text-sm leading-normal">
|
||||
No changed files are available to commit.
|
||||
</Text>
|
||||
) : !isEditingFiles ? (
|
||||
<View className="gap-2">
|
||||
{selectedFilePreview.map((file) => (
|
||||
<View key={file.path} className="flex-row items-center justify-between gap-3">
|
||||
<Text className="text-foreground flex-1 text-sm font-medium" numberOfLines={1}>
|
||||
{file.path}
|
||||
</Text>
|
||||
<Text className="text-xs font-t3-bold text-emerald-500">+{file.insertions}</Text>
|
||||
<Text className="text-xs font-t3-bold text-rose-500">-{file.deletions}</Text>
|
||||
</View>
|
||||
))}
|
||||
{selectedFiles.length > selectedFilePreview.length ? (
|
||||
<Text className="text-foreground-muted text-xs leading-snug">
|
||||
+{selectedFiles.length - selectedFilePreview.length} more files
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : (
|
||||
<View className="gap-2">
|
||||
{allFiles.map((file) => {
|
||||
const included = !excludedFiles.has(file.path);
|
||||
return (
|
||||
<Pressable
|
||||
key={file.path}
|
||||
className={cn(
|
||||
"rounded-[18px] border px-4 py-3",
|
||||
included ? "border-border" : "border-border-subtle",
|
||||
)}
|
||||
onPress={() => {
|
||||
setExcludedFiles((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(file.path)) {
|
||||
next.delete(file.path);
|
||||
} else {
|
||||
next.add(file.path);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
>
|
||||
<View
|
||||
className={`absolute inset-0 rounded-[18px] ${included ? "bg-card" : "bg-subtle"}`}
|
||||
/>
|
||||
<View className="flex-row items-start justify-between gap-3">
|
||||
<View className="flex-1 gap-1">
|
||||
<Text
|
||||
selectable
|
||||
className={`text-sm font-t3-bold ${included ? "text-foreground" : "text-foreground-muted"}`}
|
||||
>
|
||||
{file.path}
|
||||
</Text>
|
||||
) : null}
|
||||
{!included ? (
|
||||
<Text className="text-foreground-muted text-2xs leading-normal">
|
||||
Excluded from this commit
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<View className="items-end gap-1">
|
||||
<Text className="text-xs font-t3-bold text-emerald-500">
|
||||
+{file.insertions}
|
||||
</Text>
|
||||
<Text className="text-xs font-t3-bold text-rose-500">
|
||||
-{file.deletions}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View className="items-end gap-1">
|
||||
<Text className="text-xs font-t3-bold text-emerald-500">
|
||||
+{file.insertions}
|
||||
</Text>
|
||||
<Text className="text-xs font-t3-bold text-rose-500">-{file.deletions}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View className="gap-2">
|
||||
<Text className="text-foreground text-sm font-t3-bold">Commit message</Text>
|
||||
<TextInput
|
||||
multiline
|
||||
value={dialogCommitMessage}
|
||||
onChangeText={setDialogCommitMessage}
|
||||
placeholder="Leave empty to auto-generate"
|
||||
textAlignVertical="top"
|
||||
className="min-h-[128px] rounded-[20px] px-4 py-3.5"
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="flex-row gap-3">
|
||||
<View className="flex-1">
|
||||
<SheetActionButton
|
||||
icon="arrow.branch"
|
||||
label="Commit on new branch"
|
||||
disabled={noneSelected || busy}
|
||||
onPress={() => void runCommitAction(true)}
|
||||
/>
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
<SheetActionButton
|
||||
icon="checkmark.circle"
|
||||
label="Commit"
|
||||
tone="primary"
|
||||
disabled={noneSelected || busy}
|
||||
onPress={() => void runCommitAction(false)}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View className="gap-2">
|
||||
<Text className="text-foreground text-sm font-t3-bold">Commit message</Text>
|
||||
<TextInput
|
||||
multiline
|
||||
value={dialogCommitMessage}
|
||||
onChangeText={setDialogCommitMessage}
|
||||
placeholder="Leave empty to auto-generate"
|
||||
textAlignVertical="top"
|
||||
className="min-h-[128px] rounded-[20px] px-4 py-3.5"
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="flex-row gap-3">
|
||||
<View className="flex-1">
|
||||
<SheetActionButton
|
||||
icon="arrow.branch"
|
||||
label="Commit on new branch"
|
||||
disabled={noneSelected || busy}
|
||||
onPress={() => void runCommitAction(true)}
|
||||
/>
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
<SheetActionButton
|
||||
icon="checkmark.circle"
|
||||
label="Commit"
|
||||
tone="primary"
|
||||
disabled={noneSelected || busy}
|
||||
onPress={() => void runCommitAction(false)}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</ScrollView>
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -4,10 +4,11 @@ import * as Arr from "effect/Array";
|
||||
import * as Result from "effect/Result";
|
||||
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { View } from "react-native";
|
||||
import { Platform, View } from "react-native";
|
||||
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../../components/AppText";
|
||||
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
|
||||
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
|
||||
@@ -102,7 +103,11 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) {
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
<View className="min-h-4 pt-2" />
|
||||
{Platform.OS === "android" ? (
|
||||
<AndroidSheetHeader title="Confirm action" onBack={() => navigation.goBack()} />
|
||||
) : (
|
||||
<View className="min-h-4 pt-2" />
|
||||
)}
|
||||
|
||||
<View className="items-center gap-1 px-5 pb-3 pt-4">
|
||||
<Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
|
||||
|
||||
@@ -5,7 +5,12 @@ import {
|
||||
requiresDefaultBranchConfirmation,
|
||||
} from "@t3tools/client-runtime/state/vcs";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import {
|
||||
CommonActions,
|
||||
StackActions,
|
||||
useNavigation,
|
||||
type StaticScreenProps,
|
||||
} from "@react-navigation/native";
|
||||
import { SymbolView } from "../../../components/AppSymbol";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Alert, Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
|
||||
@@ -14,6 +19,7 @@ import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-scree
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../../lib/useThemeColor";
|
||||
|
||||
import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../../components/AppText";
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../../native/StackHeader";
|
||||
import { tryOpenExternalUrl } from "../../../lib/openExternalUrl";
|
||||
@@ -23,6 +29,7 @@ import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-
|
||||
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
|
||||
import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
|
||||
import { vcsEnvironment } from "../../../state/vcs";
|
||||
import { resolveGitOverviewReviewNavigationAction } from "./git-overview-navigation";
|
||||
import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents";
|
||||
|
||||
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
@@ -255,7 +262,14 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
|
||||
title="Review changes"
|
||||
subtitle="Inspect turn diffs, worktree changes, and base branch diff"
|
||||
disabled={busy || !isRepo}
|
||||
onPress={() => navigation.navigate("ThreadReview", { environmentId, threadId })}
|
||||
onPress={() => {
|
||||
const params = { environmentId, threadId };
|
||||
navigation.dispatch(
|
||||
resolveGitOverviewReviewNavigationAction(presentation) === "replace"
|
||||
? StackActions.replace("ThreadReview", params)
|
||||
: CommonActions.navigate("ThreadReview", params),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<View className="ml-12 h-px bg-border" />
|
||||
<SheetListRow
|
||||
@@ -348,12 +362,14 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
|
||||
collapsable={false}
|
||||
className={isInspector ? "flex-1 border-l border-border bg-sheet" : "flex-1 bg-sheet"}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
minHeight: isInspector ? (props.headerInset ?? 0) : 16,
|
||||
paddingTop: isInspector ? (props.headerInset ?? 0) : 8,
|
||||
}}
|
||||
/>
|
||||
{isInspector ? (
|
||||
<View
|
||||
style={{
|
||||
minHeight: props.headerInset ?? 0,
|
||||
paddingTop: props.headerInset ?? 0,
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{isInspector ? (
|
||||
<View className="gap-1 border-b border-border px-4 pb-4 pt-3">
|
||||
@@ -383,24 +399,19 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
// Compact header row: labeled branch on the left, status summary at
|
||||
// the trailing end. Horizontal padding lines the text up with the
|
||||
// rows' icon column inside the card below (20 screen + 16 card + 4
|
||||
// row). The sheet relies on pull-to-refresh instead of a corner
|
||||
// refresh button.
|
||||
<View className="flex-row items-end justify-between gap-3 px-10 pb-4 pt-4">
|
||||
<View className="shrink gap-0.5">
|
||||
<Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
|
||||
Branch
|
||||
</Text>
|
||||
<Text className="text-xl font-t3-bold" numberOfLines={1}>
|
||||
{currentBranchLabel}
|
||||
</Text>
|
||||
</View>
|
||||
<Text className="text-foreground-secondary pb-0.5 text-sm font-medium" numberOfLines={1}>
|
||||
{currentStatusSummary}
|
||||
</Text>
|
||||
</View>
|
||||
<AndroidSheetHeader
|
||||
title={currentBranchLabel}
|
||||
subtitle={currentStatusSummary}
|
||||
onBack={() => navigation.goBack()}
|
||||
actions={[
|
||||
{
|
||||
accessibilityLabel: "Refresh repository status",
|
||||
disabled: busy,
|
||||
icon: "arrow.clockwise",
|
||||
onPress: () => void gitActions.refreshSelectedThreadGitStatus(),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
|
||||
{content}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveGitOverviewReviewNavigationAction } from "./git-overview-navigation";
|
||||
|
||||
describe("resolveGitOverviewReviewNavigationAction", () => {
|
||||
it("replaces the sheet so Back returns directly to the thread", () => {
|
||||
expect(resolveGitOverviewReviewNavigationAction("sheet")).toBe("replace");
|
||||
});
|
||||
|
||||
it("pushes Review normally when Git is a persistent inspector", () => {
|
||||
expect(resolveGitOverviewReviewNavigationAction("inspector")).toBe("navigate");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
export function resolveGitOverviewReviewNavigationAction(
|
||||
presentation: "sheet" | "inspector",
|
||||
): "replace" | "navigate" {
|
||||
return presentation === "sheet" ? "replace" : "navigate";
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export function estimateBase64ByteSize(base64: string): number {
|
||||
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
|
||||
return Math.floor((base64.length * 3) / 4) - padding;
|
||||
}
|
||||
@@ -36,7 +36,37 @@ vi.mock("./uuid", () => ({
|
||||
uuidv4: () => "attachment-id",
|
||||
}));
|
||||
|
||||
import { convertPastedImagesToAttachments, isOwnedPastedImageUri } from "./composerImages";
|
||||
import {
|
||||
convertPastedImagesToAttachments,
|
||||
isOwnedPastedImageUri,
|
||||
toUploadChatImageAttachments,
|
||||
} from "./composerImages";
|
||||
|
||||
describe("toUploadChatImageAttachments", () => {
|
||||
it("strips client draft id and previewUri for the startTurn wire shape", () => {
|
||||
expect(
|
||||
toUploadChatImageAttachments([
|
||||
{
|
||||
id: "client-draft-id",
|
||||
type: "image",
|
||||
name: "pasted-image.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 12,
|
||||
dataUrl: "data:image/png;base64,AA==",
|
||||
previewUri: "file:///tmp/preview.png",
|
||||
},
|
||||
]),
|
||||
).toEqual([
|
||||
{
|
||||
type: "image",
|
||||
name: "pasted-image.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 12,
|
||||
dataUrl: "data:image/png;base64,AA==",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("native pasted image cleanup", () => {
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type UploadChatImageAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
import { estimateBase64ByteSize } from "./base64";
|
||||
import { uuidv4 } from "./uuid";
|
||||
|
||||
export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
|
||||
@@ -10,13 +11,21 @@ export interface DraftComposerImageAttachment extends UploadChatImageAttachment
|
||||
readonly previewUri: string;
|
||||
}
|
||||
|
||||
const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
|
||||
|
||||
function estimateBase64ByteSize(base64: string): number {
|
||||
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
|
||||
return Math.floor((base64.length * 3) / 4) - padding;
|
||||
/** Wire shape for startTurn: pure uploads without client draft id / previewUri. */
|
||||
export function toUploadChatImageAttachments(
|
||||
attachments: ReadonlyArray<DraftComposerImageAttachment>,
|
||||
): ReadonlyArray<UploadChatImageAttachment> {
|
||||
return attachments.map((attachment) => ({
|
||||
type: attachment.type,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
dataUrl: attachment.dataUrl,
|
||||
}));
|
||||
}
|
||||
|
||||
const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
|
||||
|
||||
async function loadImagePicker() {
|
||||
try {
|
||||
return await import("expo-image-picker");
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { DraftComposerImageAttachment } from "./composerImages";
|
||||
import { toUploadChatImageAttachments, type DraftComposerImageAttachment } from "./composerImages";
|
||||
|
||||
export function deriveThreadTitleFromPrompt(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
@@ -55,7 +55,7 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe
|
||||
messageId: MessageId.make(spec.messageId),
|
||||
role: "user" as const,
|
||||
text: spec.text,
|
||||
attachments: spec.attachments,
|
||||
attachments: toUploadChatImageAttachments(spec.attachments),
|
||||
},
|
||||
modelSelection: spec.modelSelection,
|
||||
titleSeed: title,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { SerializedAsyncQueue } from "./serialized-async-queue";
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>((next) => {
|
||||
resolve = next;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
describe("SerializedAsyncQueue", () => {
|
||||
it("does not let a newer operation overtake an in-flight operation", async () => {
|
||||
const queue = new SerializedAsyncQueue();
|
||||
const firstGate = deferred();
|
||||
const events: string[] = [];
|
||||
|
||||
const first = queue.run(async () => {
|
||||
events.push("first:start");
|
||||
await firstGate.promise;
|
||||
events.push("first:end");
|
||||
});
|
||||
const second = queue.run(async () => {
|
||||
events.push("second");
|
||||
});
|
||||
|
||||
await Promise.resolve();
|
||||
expect(events).toEqual(["first:start"]);
|
||||
firstGate.resolve();
|
||||
await Promise.all([first, second]);
|
||||
expect(events).toEqual(["first:start", "first:end", "second"]);
|
||||
});
|
||||
|
||||
it("continues after a rejected operation", async () => {
|
||||
const queue = new SerializedAsyncQueue();
|
||||
const first = queue.run(async () => {
|
||||
throw new Error("failed");
|
||||
});
|
||||
const second = queue.run(async () => "recovered");
|
||||
|
||||
await expect(first).rejects.toThrow("failed");
|
||||
await expect(second).resolves.toBe("recovered");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Runs asynchronous operations in call order while keeping the queue usable
|
||||
* after an individual operation rejects.
|
||||
*/
|
||||
export class SerializedAsyncQueue {
|
||||
private tail: Promise<void> = Promise.resolve();
|
||||
|
||||
run<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const result = this.tail.then(operation, operation);
|
||||
this.tail = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -195,7 +195,7 @@ function convertToolbarChild(child: ReactNode): NativeStackHeaderItem | null {
|
||||
if (typeName === "NativeHeaderToolbarButton") {
|
||||
return {
|
||||
type: "button",
|
||||
label: "",
|
||||
label: typeof child.props.label === "string" ? child.props.label : "",
|
||||
accessibilityLabel:
|
||||
typeof child.props.accessibilityLabel === "string"
|
||||
? child.props.accessibilityLabel
|
||||
@@ -293,6 +293,7 @@ function NativeHeaderToolbarButton(_props: {
|
||||
readonly accessibilityLabel?: string;
|
||||
readonly disabled?: boolean;
|
||||
readonly icon?: string;
|
||||
readonly label?: string;
|
||||
readonly onPress?: () => void;
|
||||
readonly separateBackground?: boolean;
|
||||
readonly tintColor?: ColorValue;
|
||||
|
||||
@@ -101,7 +101,10 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
cause,
|
||||
});
|
||||
}
|
||||
setMessages([...currentMessages(), message]);
|
||||
setMessages([
|
||||
...currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
|
||||
message,
|
||||
]);
|
||||
});
|
||||
|
||||
// Rewrites an already-queued message. A no-op when the message has been
|
||||
|
||||
@@ -294,6 +294,31 @@ describe("thread outbox", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("replaces an existing message when an enqueue retry uses the same id", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
write: async () => undefined,
|
||||
remove: async () => undefined,
|
||||
},
|
||||
});
|
||||
const message = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const retried = { ...message, text: "retried" };
|
||||
|
||||
await manager.enqueue(message);
|
||||
await manager.enqueue(retried);
|
||||
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [retried],
|
||||
});
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("updates a queued message in place but never resurrects a removed one", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const stored = new Map<MessageId, QueuedThreadMessage>();
|
||||
|
||||
@@ -8,7 +8,9 @@ import {
|
||||
decodePersistedComposerDrafts,
|
||||
type ComposerDraft,
|
||||
getComposerDraftSnapshot,
|
||||
mergeComposerDraftContentState,
|
||||
removeComposerDraftsForEnvironment,
|
||||
restoreComposerDraftSnapshotState,
|
||||
} from "./use-composer-drafts";
|
||||
|
||||
const DRAFT: ComposerDraft = {
|
||||
@@ -94,6 +96,7 @@ describe("mobile composer drafts", () => {
|
||||
const draft: ComposerDraft = {
|
||||
text: "send this",
|
||||
attachments: [],
|
||||
importedShareIds: ["share-1"],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
@@ -108,7 +111,8 @@ describe("mobile composer drafts", () => {
|
||||
|
||||
expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
|
||||
[draftKey]: {
|
||||
...draft,
|
||||
modelSelection: draft.modelSelection,
|
||||
workspaceSelection: draft.workspaceSelection,
|
||||
text: "",
|
||||
attachments: [],
|
||||
},
|
||||
@@ -131,6 +135,90 @@ describe("mobile composer drafts", () => {
|
||||
expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
|
||||
});
|
||||
|
||||
it("merges shared content into a project draft without duplicating retries", () => {
|
||||
const draftKey = "new-task:environment-1:project-1";
|
||||
const sharedAttachment = {
|
||||
id: "share-1:image:0",
|
||||
type: "image" as const,
|
||||
name: "Screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 3,
|
||||
dataUrl: "data:image/png;base64,YWJj",
|
||||
previewUri: "data:image/png;base64,YWJj",
|
||||
};
|
||||
const existing: Record<string, ComposerDraft> = {
|
||||
[draftKey]: { text: "Existing context", attachments: [] },
|
||||
};
|
||||
const content = {
|
||||
text: "Shared note",
|
||||
attachments: [sharedAttachment],
|
||||
sourceShareId: "share-1",
|
||||
};
|
||||
|
||||
const merged = mergeComposerDraftContentState(existing, draftKey, content);
|
||||
expect(merged[draftKey]).toMatchObject({
|
||||
text: "Existing context\n\nShared note",
|
||||
attachments: [sharedAttachment],
|
||||
importedShareIds: ["share-1"],
|
||||
});
|
||||
expect(mergeComposerDraftContentState(merged, draftKey, content)).toBe(merged);
|
||||
|
||||
const edited = {
|
||||
...merged,
|
||||
[draftKey]: { ...merged[draftKey]!, text: "User edited the imported context" },
|
||||
};
|
||||
expect(mergeComposerDraftContentState(edited, draftKey, content)).toBe(edited);
|
||||
});
|
||||
|
||||
it("preserves existing images when shared content exceeds the draft attachment limit", () => {
|
||||
const draftKey = "new-task:environment-1:project-1";
|
||||
const image = (id: string) => ({
|
||||
id,
|
||||
type: "image" as const,
|
||||
name: `${id}.png`,
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 3,
|
||||
dataUrl: "data:image/png;base64,YWJj",
|
||||
previewUri: "data:image/png;base64,YWJj",
|
||||
});
|
||||
const existingImage = image("existing");
|
||||
const sharedImages = Array.from({ length: 8 }, (_, index) => image(`shared-${index}`));
|
||||
|
||||
const merged = mergeComposerDraftContentState(
|
||||
{ [draftKey]: { text: "", attachments: [existingImage] } },
|
||||
draftKey,
|
||||
{ text: "", attachments: sharedImages },
|
||||
);
|
||||
|
||||
expect(merged[draftKey]?.attachments).toHaveLength(8);
|
||||
expect(merged[draftKey]?.attachments[0]).toEqual(existingImage);
|
||||
expect(merged[draftKey]?.attachments.at(-1)?.id).toBe("shared-6");
|
||||
});
|
||||
|
||||
it("restores the exact draft captured before an interrupted share import", () => {
|
||||
const draftKey = "new-task:environment-1:project-1";
|
||||
const beforeImport: ComposerDraft = {
|
||||
text: "Existing context",
|
||||
attachments: [],
|
||||
runtimeMode: "approval-required",
|
||||
};
|
||||
const imported: ComposerDraft = {
|
||||
...beforeImport,
|
||||
text: "Existing context\n\nShared note",
|
||||
importedShareIds: ["share-1"],
|
||||
};
|
||||
|
||||
expect(
|
||||
restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, beforeImport),
|
||||
).toEqual({ [draftKey]: beforeImport });
|
||||
expect(
|
||||
restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, {
|
||||
text: "",
|
||||
attachments: [],
|
||||
}),
|
||||
).toEqual({});
|
||||
});
|
||||
|
||||
it("removes only drafts owned by the selected environment", () => {
|
||||
const environmentId = EnvironmentId.make("environment-cloud");
|
||||
const retainedEnvironmentId = EnvironmentId.make("environment-local");
|
||||
|
||||