Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex e5f5c40fdc Add scoped SSH preview port forwarding
Co-authored-by: codex <[email protected]>
2026-07-16 11:51:02 +02:00
Julius Marmingeandcodex bde0a4c0dd Resolve localhost preview URLs for remote environments (#4011)
Co-authored-by: codex <[email protected]>
2026-07-16 11:07:38 +02:00
Julius Marmingeandcodex 54f167e2e0 Normalize over-indented markdown list items (#4020)
Co-authored-by: codex <[email protected]>
2026-07-16 08:47:36 +00:00
Julius Marmingeandcodex d114e2772d Prevent duplicate project workspace roots (#3829)
Co-authored-by: codex <[email protected]>
2026-07-16 10:39:13 +02:00
Ishan 0418301de7 Fix macOS fullscreen titlebar spacing (#4019) 2026-07-16 09:34:33 +02:00
Julius Marminge 5e8b2c800e Isolate native diff highlight grammar state (#4029) 2026-07-16 09:24:41 +02:00
Julius Marmingeandcodex b98233702c [codex] Fix onboarding connection status (#4001)
Co-authored-by: codex <[email protected]>
2026-07-16 09:22:07 +02:00
Julius Marmingeandcodex ecb35f7583 Fix Legal modal header crash (#4000)
Co-authored-by: codex <[email protected]>
2026-07-15 10:48:55 +00:00
Julius Marmingeandcodex d359789ed4 docs: Add T3 Code Legal Docs (#3972)
Co-authored-by: codex <[email protected]>
2026-07-15 11:44:03 +02:00
Kriday Dave 462442667e fix(docs): replace stale codething-mvp absolute paths with repo-relative links (#3992) 2026-07-15 10:55:01 +02:00
Kriday Dave c69120f484 fix(docs): repair broken source links in architecture overview (#3991) 2026-07-15 10:54:40 +02:00
Kriday Dave 7b928d5488 fix(docs): correct CI task-runner commands in ci.md (#3990) 2026-07-15 10:53:48 +02:00
Theo Browne 2fdc704bbb perf(web): duty-cycle status animations and remove fixed noise overlay (#3978) 2026-07-15 09:08:33 +02:00
Julius Marminge 3513fa04fb Prepare Android beta branding and review diff UI (#3967) 2026-07-14 19:21:12 +02:00
Julius Marminge 735240f316 Skip stale working-task notifications (#3961) 2026-07-14 18:00:16 +02:00
Julius Marminge 8de254a685 Use client-side fallbacks for missing project favicons (#3959) 2026-07-14 17:59:00 +02:00
120 changed files with 6560 additions and 1064 deletions

No files matched your search

@@ -14,6 +14,7 @@ import {
setTailscaleServeEnabled,
} from "./methods/serverExposure.ts";
import {
acquireSshPortForward,
bootstrapSshBearerSession,
disconnectSshEnvironment,
discoverSshHosts,
@@ -21,6 +22,7 @@ import {
fetchSshEnvironmentDescriptor,
fetchSshSessionState,
issueSshWebSocketTicket,
releaseSshPortForward,
resolveSshPasswordPrompt,
} from "./methods/sshEnvironment.ts";
import {
@@ -35,6 +37,7 @@ import {
getAppBranding,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
getWindowFullscreenState,
openExternal,
pickFolder,
setTheme,
@@ -48,6 +51,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);
@@ -60,6 +64,8 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(discoverSshHosts);
yield* ipc.handle(ensureSshEnvironment);
yield* ipc.handle(disconnectSshEnvironment);
yield* ipc.handle(acquireSshPortForward);
yield* ipc.handle(releaseSshPortForward);
yield* ipc.handle(fetchSshEnvironmentDescriptor);
yield* ipc.handle(bootstrapSshBearerSession);
yield* ipc.handle(fetchSshSessionState);
+4
View File
@@ -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";
@@ -22,6 +24,8 @@ export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalo
export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
export const ACQUIRE_SSH_PORT_FORWARD_CHANNEL = "desktop:acquire-ssh-port-forward";
export const RELEASE_SSH_PORT_FORWARD_CHANNEL = "desktop:release-ssh-port-forward";
export const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
export const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
export const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
@@ -8,9 +8,12 @@ import * as Option from "effect/Option";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import {
acquireSshPortForward,
DesktopSshEnvironmentRequestError,
fetchSshEnvironmentDescriptor,
releaseSshPortForward,
} from "./sshEnvironment.ts";
import { DesktopSshEnvironment } from "../../ssh/DesktopSshEnvironment.ts";
function jsonResponse(request: HttpClientRequest.HttpClientRequest, body: unknown, status = 200) {
return HttpClientResponse.fromWeb(
@@ -34,6 +37,41 @@ function makeHttpClientLayer(
}
describe("SSH environment IPC", () => {
it.effect("acquires and releases SSH port-forward leases", () => {
const calls: unknown[] = [];
const target = {
alias: "devbox",
hostname: "devbox.example.test",
username: "developer",
port: 22,
} as const;
const layer = Layer.succeed(
DesktopSshEnvironment,
DesktopSshEnvironment.of({
discoverHosts: () => Effect.succeed([]),
ensureEnvironment: () => Effect.die("unused"),
disconnectEnvironment: () => Effect.die("unused"),
acquirePortForward: (receivedTarget, remotePort) =>
Effect.sync(() => {
calls.push([receivedTarget, remotePort]);
return { leaseId: "lease-1", localPort: 42_173, remotePort };
}),
releasePortForward: (leaseId) => Effect.sync(() => void calls.push(leaseId)),
}),
);
return Effect.gen(function* () {
const acquired = yield* acquireSshPortForward.handler({ target, remotePort: 5173 });
assert.deepEqual(acquired, {
leaseId: "lease-1",
localPort: 42_173,
remotePort: 5173,
});
yield* releaseSshPortForward.handler({ leaseId: "lease-1" });
assert.deepEqual(calls, [[target, 5173], "lease-1"]);
}).pipe(Effect.provide(layer));
});
it.effect("fetches and decodes the remote environment descriptor", () => {
const requestUrls: string[] = [];
const layer = makeHttpClientLayer((request) =>
@@ -15,6 +15,9 @@ import {
DesktopSshEnvironmentEnsureResultSchema,
DesktopSshEnvironmentTargetSchema,
DesktopSshHttpBaseUrlInputSchema,
DesktopSshPortForwardAcquireInputSchema,
DesktopSshPortForwardAcquireResultSchema,
DesktopSshPortForwardReleaseInputSchema,
DesktopSshPasswordPromptCancelledType,
DesktopSshPasswordPromptResolutionInputSchema,
ExecutionEnvironmentDescriptor,
@@ -149,6 +152,38 @@ export const disconnectSshEnvironment = DesktopIpc.makeIpcMethod({
}),
});
export const acquireSshPortForward = DesktopIpc.makeIpcMethod({
channel: IpcChannels.ACQUIRE_SSH_PORT_FORWARD_CHANNEL,
payload: DesktopSshPortForwardAcquireInputSchema,
result: DesktopSshPortForwardAcquireResultSchema,
handler: Effect.fn("desktop.ipc.sshEnvironment.acquirePortForward")(function* ({
target,
remotePort,
}) {
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
return yield* sshEnvironment.acquirePortForward(target, remotePort).pipe(
Effect.catch((error) =>
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(error)
? Effect.succeed({
type: DesktopSshPasswordPromptCancelledType,
message: error.message,
})
: Effect.fail(error),
),
);
}),
});
export const releaseSshPortForward = DesktopIpc.makeIpcMethod({
channel: IpcChannels.RELEASE_SSH_PORT_FORWARD_CHANNEL,
payload: DesktopSshPortForwardReleaseInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.sshEnvironment.releasePortForward")(function* ({ leaseId }) {
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
yield* sshEnvironment.releasePortForward(leaseId);
}),
});
export const fetchSshEnvironmentDescriptor = DesktopIpc.makeIpcMethod({
channel: IpcChannels.FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL,
payload: DesktopSshHttpBaseUrlInputSchema,
+21 -1
View File
@@ -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)),
}),
),
);
});
});
+10
View File
@@ -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),
+25 -3
View File
@@ -11,7 +11,7 @@ import * as IpcChannels from "./ipc/channels.ts";
exposeClerkBridge({ passkeys: true });
function unwrapEnsureSshEnvironmentResult(result: unknown) {
function unwrapSshPasswordPromptResult<T>(result: unknown): T {
if (
typeof result === "object" &&
result !== null &&
@@ -24,7 +24,7 @@ function unwrapEnsureSshEnvironmentResult(result: unknown) {
: "SSH authentication cancelled.";
throw new Error(message);
}
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
return result as T;
}
contextBridge.exposeInMainWorld("desktopBridge", {
@@ -53,7 +53,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
clearConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL),
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
ensureSshEnvironment: async (target, options) =>
unwrapEnsureSshEnvironmentResult(
unwrapSshPasswordPromptResult<Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>>(
await ipcRenderer.invoke(IpcChannels.ENSURE_SSH_ENVIRONMENT_CHANNEL, {
target,
...(options === undefined ? {} : { options }),
@@ -61,6 +61,15 @@ contextBridge.exposeInMainWorld("desktopBridge", {
),
disconnectSshEnvironment: (target) =>
ipcRenderer.invoke(IpcChannels.DISCONNECT_SSH_ENVIRONMENT_CHANNEL, target),
acquireSshPortForward: async (target, remotePort) =>
unwrapSshPasswordPromptResult<Awaited<ReturnType<DesktopBridge["acquireSshPortForward"]>>>(
await ipcRenderer.invoke(IpcChannels.ACQUIRE_SSH_PORT_FORWARD_CHANNEL, {
target,
remotePort,
}),
),
releaseSshPortForward: (leaseId) =>
ipcRenderer.invoke(IpcChannels.RELEASE_SSH_PORT_FORWARD_CHANNEL, { leaseId }),
fetchSshEnvironmentDescriptor: (httpBaseUrl) =>
ipcRenderer.invoke(IpcChannels.FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, { httpBaseUrl }),
bootstrapSshBearerSession: (httpBaseUrl, credential) =>
@@ -116,6 +125,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),
@@ -61,6 +61,11 @@ export class DesktopSshEnvironment extends Context.Service<
readonly disconnectEnvironment: (
target: DesktopSshEnvironmentTarget,
) => Effect.Effect<void, DesktopSshEnvironmentOperationError>;
readonly acquirePortForward: (
target: DesktopSshEnvironmentTarget,
remotePort: number,
) => Effect.Effect<SshTunnel.SshPortForwardLease, DesktopSshEnvironmentOperationError>;
readonly releasePortForward: (leaseId: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/ssh/DesktopSshEnvironment") {}
@@ -152,6 +157,16 @@ export const make = Effect.gen(function* () {
Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.disconnectEnvironment"),
),
acquirePortForward: (target, remotePort) =>
manager
.acquirePortForward(target, remotePort)
.pipe(
Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
Effect.provide(runtimeContext),
Effect.withSpan("desktop.ssh.acquirePortForward"),
),
releasePortForward: (leaseId) =>
manager.releasePortForward(leaseId).pipe(Effect.withSpan("desktop.ssh.releasePortForward")),
});
});
+38 -2
View File
@@ -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();
+10 -1
View File
@@ -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 = () => {
@@ -75,6 +75,7 @@ const backendConfigurationLayer = Layer.succeed(
);
const netLayer = Layer.succeed(NetService.NetService, {
hasListenerOnHost: () => Effect.succeed(false),
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(41773),
@@ -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">&#8592;</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>
+31 -2
View File
@@ -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) {
+172
View File
@@ -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">&#8599;</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>
+47 -31
View File
@@ -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) {
@@ -121,7 +129,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,7 +138,7 @@ const config: ExpoConfig = {
fallbackToCacheTimeout: 0,
},
ios: {
icon: variant.iosIcon,
icon: variant.assets.iosIcon,
supportsTablet: true,
bundleIdentifier: variant.iosBundleIdentifier,
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
@@ -151,13 +159,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 +172,7 @@ const config: ExpoConfig = {
predictiveBackGestureEnabled: true,
},
web: {
favicon: "./assets/favicon.png",
favicon: variant.assets.appIcon,
},
plugins: [
"expo-asset",
@@ -195,6 +202,14 @@ const config: ExpoConfig = {
],
"expo-secure-store",
"expo-sqlite",
[
"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 +221,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 +232,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",
},
},
File renamed without changes.

Before

Width:  |  Height:  |  Size: 323 KiB

After

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 733 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

@@ -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() }
+1 -1
View File
@@ -5,7 +5,7 @@
"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",
+25 -3
View File
@@ -44,8 +44,13 @@ 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 {
SettingsLegalDocumentCloseHeaderButton,
SettingsLegalDocumentExternalHeaderButton,
} from "./features/settings/components/SettingsLegalDocumentRouteScreen";
import { useAppShortcuts } from "./features/shortcuts/useAppShortcuts";
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
@@ -106,6 +111,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 +252,7 @@ const WORKSPACE_OVERLAY_ROUTES = new Set([
"GitConfirm",
"GitOverview",
"NewTaskSheet",
"SettingsLegal",
"SettingsSheet",
"ThreadReviewComment",
]);
@@ -436,13 +450,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 />;
}
@@ -3,6 +3,7 @@ import { Image } from "expo-image";
import { useState } from "react";
import { View } from "react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon";
import { useThemeColor } from "../lib/useThemeColor";
import { useAssetUrl } from "../state/assets";
@@ -24,11 +25,12 @@ export function ProjectFavicon(props: {
? null
: { _tag: "project-favicon", cwd: props.workspaceRoot },
);
const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl;
return (
<ProjectFaviconImage
key={faviconUrl}
faviconUrl={faviconUrl}
faviconUrl={renderableFaviconUrl}
open={props.open}
projectTitle={props.projectTitle}
size={size}
+7
View File
@@ -161,6 +161,13 @@ const capabilitiesLayer = Layer.effectContext(
}),
),
disconnect: () => Effect.void,
forwardPort: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
detail: "SSH environments are only available in the desktop app.",
}),
),
}),
),
);
@@ -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"
@@ -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();
@@ -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&apos;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);
}
@@ -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";
}
+3 -1
View File
@@ -1,5 +1,6 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ThreadId } from "@t3tools/contracts";
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -228,6 +229,7 @@ describe("AssetAccess", () => {
const fallbackResult = yield* issueAssetUrl({
resource: { _tag: "project-favicon", cwd: root },
});
expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
expect(
@@ -235,7 +237,7 @@ describe("AssetAccess", () => {
fallbackSuffix.slice(0, fallbackSeparatorIndex),
fallbackSuffix.slice(fallbackSeparatorIndex + 1),
),
).toEqual({ kind: "project-favicon-fallback" });
).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
+4 -8
View File
@@ -19,6 +19,7 @@ import {
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
} from "@t3tools/shared/filePreview";
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -40,7 +41,6 @@ import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
export const ASSET_ROUTE_PREFIX = "/api/assets";
export const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
const SIGNING_SECRET_NAME = "asset-access-signing-key";
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
@@ -91,9 +91,7 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
export type ResolvedAsset =
| { readonly kind: "file"; readonly path: string }
| { readonly kind: "project-favicon-fallback" };
export type ResolvedAsset = { readonly kind: "file"; readonly path: string };
function decodeClaims(encodedPayload: string): AssetClaims | null {
try {
@@ -326,7 +324,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
relativePath,
expiresAt,
};
fileName = relativePath ? path.basename(relativePath) : "favicon.svg";
fileName = relativePath ? path.basename(relativePath) : PROJECT_FAVICON_FALLBACK_MARKER;
break;
}
}
@@ -391,9 +389,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
}
if (claims.kind === "project-favicon") {
if (claims.relativePath === null) {
return { kind: "project-favicon-fallback" } satisfies ResolvedAsset;
}
if (claims.relativePath === null) return null;
const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
workspaceRoot: claims.workspaceRoot,
relativePath: claims.relativePath,
+1 -16
View File
@@ -25,11 +25,7 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import { OtlpTracer } from "effect/unstable/observability";
import * as ServerConfig from "./config.ts";
import {
ASSET_ROUTE_PREFIX,
FALLBACK_PROJECT_FAVICON_SVG,
resolveAsset,
} from "./assets/AssetAccess.ts";
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
@@ -196,17 +192,6 @@ export const assetRouteLayer = HttpRouter.add(
if (!asset) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
if (asset.kind === "project-favicon-fallback") {
return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
status: 200,
contentType: "image/svg+xml",
headers: {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
},
});
}
return yield* HttpServerResponse.file(asset.path, {
status: 200,
headers: {
@@ -6,6 +6,7 @@ import type {
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
import * as Effect from "effect/Effect";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
@@ -71,6 +72,30 @@ export function requireProjectAbsent(input: {
);
}
export function requireActiveProjectWorkspaceRootAbsent(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly workspaceRoot: string;
readonly exceptProjectId?: ProjectId;
}): Effect.Effect<void, OrchestrationCommandInvariantError> {
const normalizedWorkspaceRoot = normalizeProjectPathForComparison(input.workspaceRoot);
const existingProject = input.readModel.projects.find(
(project) =>
project.deletedAt === null &&
normalizeProjectPathForComparison(project.workspaceRoot) === normalizedWorkspaceRoot &&
project.id !== input.exceptProjectId,
);
if (existingProject === undefined) {
return Effect.void;
}
return Effect.fail(
invariantError(
input.command.type,
`Active project '${existingProject.id}' already exists for workspace root '${normalizedWorkspaceRoot}'.`,
),
);
}
export function requireThread(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
@@ -94,6 +94,117 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
}),
);
it.effect("rejects project.create for an active workspace root that already exists", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const readModel = yield* projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
aggregateId: asProjectId("project-existing"),
type: "project.created",
occurredAt: now,
commandId: CommandId.make("cmd-project-create"),
causationEventId: null,
correlationId: CommandId.make("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-existing"),
title: "Project",
workspaceRoot: "/tmp/project",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
const failure = yield* Effect.flip(
decideOrchestrationCommand({
command: {
type: "project.create",
commandId: CommandId.make("cmd-project-create-duplicate-root"),
projectId: asProjectId("project-duplicate-root"),
title: "Duplicate Project",
workspaceRoot: "/tmp/project/",
createdAt: now,
},
readModel,
}),
);
expect(failure.message).toContain(
"Active project 'project-existing' already exists for workspace root '/tmp/project'.",
);
}),
);
it.effect("rejects project.meta.update when moving onto another active workspace root", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withFirstProject = yield* projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create-first"),
aggregateKind: "project",
aggregateId: asProjectId("project-first"),
type: "project.created",
occurredAt: now,
commandId: CommandId.make("cmd-project-create-first"),
causationEventId: null,
correlationId: CommandId.make("cmd-project-create-first"),
metadata: {},
payload: {
projectId: asProjectId("project-first"),
title: "First",
workspaceRoot: "/tmp/project-first",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
const readModel = yield* projectEvent(withFirstProject, {
sequence: 2,
eventId: asEventId("evt-project-create-second"),
aggregateKind: "project",
aggregateId: asProjectId("project-second"),
type: "project.created",
occurredAt: now,
commandId: CommandId.make("cmd-project-create-second"),
causationEventId: null,
correlationId: CommandId.make("cmd-project-create-second"),
metadata: {},
payload: {
projectId: asProjectId("project-second"),
title: "Second",
workspaceRoot: "/tmp/project-second",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
const failure = yield* Effect.flip(
decideOrchestrationCommand({
command: {
type: "project.meta.update",
commandId: CommandId.make("cmd-project-update-duplicate-root"),
projectId: asProjectId("project-second"),
workspaceRoot: "/tmp/project-first",
},
readModel,
}),
);
expect(failure.message).toContain(
"Active project 'project-first' already exists for workspace root '/tmp/project-first'.",
);
}),
);
it.effect("emits user message and turn-start-requested events for thread.turn.start", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
+15
View File
@@ -12,6 +12,7 @@ import type * as PlatformError from "effect/PlatformError";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
import {
listThreadsByProjectId,
requireActiveProjectWorkspaceRootAbsent,
requireProject,
requireProjectAbsent,
requireThread,
@@ -111,6 +112,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
projectId: command.projectId,
});
yield* requireActiveProjectWorkspaceRootAbsent({
readModel,
command,
workspaceRoot: command.workspaceRoot,
exceptProjectId: command.projectId,
});
return {
...(yield* withEventBase({
@@ -138,6 +145,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
projectId: command.projectId,
});
if (command.workspaceRoot !== undefined) {
yield* requireActiveProjectWorkspaceRootAbsent({
readModel,
command,
workspaceRoot: command.workspaceRoot,
exceptProjectId: command.projectId,
});
}
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
@@ -35,6 +35,7 @@ const makeProbeFailureLayer = (run: ProcessRunner.ProcessRunner["Service"]["run"
Layer.mergeAll(
Layer.succeed(ProcessRunner.ProcessRunner, { run }),
Layer.succeed(Net.NetService, {
hasListenerOnHost: () => Effect.succeed(false),
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(40_000),
@@ -974,8 +974,13 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
if (String(event.threadId) !== String(threadId)) {
return;
}
if (event.type === "request.opened" && !interrupted) {
if (event.type === "request.opened" && event.requestId && !interrupted) {
interrupted = true;
yield* adapter.respondToRequest(
threadId,
ApprovalRequestId.make(String(event.requestId)),
"cancel",
);
yield* adapter.interruptTurn(threadId);
return;
}
@@ -1030,15 +1035,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
entry.result.outcome !== null &&
"outcome" in entry.result.outcome &&
entry.result.outcome.outcome === "cancelled";
const cancelRequests = yield* waitForJsonLogMatch(
requestLogPath,
(entry) => entry.method === "session/cancel",
);
const approvalResponses = yield* waitForJsonLogMatch(
requestLogPath,
isCancelledApprovalResponse,
);
assert.isTrue(cancelRequests.some((entry) => entry.method === "session/cancel"));
assert.isTrue(approvalResponses.some(isCancelledApprovalResponse));
yield* adapter.stopSession(threadId);
@@ -137,7 +137,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
expect(AgentAwarenessRelay.eventThreadId(event)).toBe(threadId);
});
it("does not publish streaming content or non-awareness activity events", () => {
it("does not publish start intents, streaming content, or non-awareness activity events", () => {
const now = "2026-05-25T00:00:00.000Z";
const base = {
sequence: 1,
@@ -191,7 +191,16 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
streaming: false,
},
} as unknown as OrchestrationEvent),
).toBe(true);
).toBe(false);
expect(
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
...base,
type: "thread.turn-start-requested",
payload: {
threadId: "thread-1" as ThreadId,
},
} as unknown as OrchestrationEvent),
).toBe(false);
});
it("deduplicates awareness state updates whose only change is their event timestamp", () => {
+7 -1
View File
@@ -67,7 +67,13 @@ export function eventThreadId(event: OrchestrationEvent): ThreadId | null {
export function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boolean {
switch (event.type) {
case "thread.message-sent":
return !event.payload.streaming;
case "thread.turn-start-requested":
// These events express intent to start work, but the shell still contains
// the previous turn's terminal state until the provider acknowledges the
// new turn. Publishing that snapshot can queue a fresh "Done" alert just
// before the real running state arrives. Provider lifecycle events publish
// the authoritative starting/running state instead.
return false;
case "thread.proposed-plan-upserted":
case "thread.runtime-mode-set":
case "thread.interaction-mode-set":
@@ -1,81 +0,0 @@
import { EnvironmentId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const readPreparedConnection = vi.fn();
vi.mock("~/state/session", () => ({ readPreparedConnection }));
describe("browser target resolver", () => {
beforeEach(() => readPreparedConnection.mockReset());
it("maps environment ports onto a private network host", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://192.168.1.25:3773" });
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
expect(
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
kind: "environment-port",
port: 5173,
path: "/dashboard",
}),
).toEqual({
requestedUrl: "http://localhost:5173/dashboard",
resolvedUrl: "http://192.168.1.25:5173/dashboard",
resolutionKind: "direct-private-network",
environmentId: "environment-1",
});
});
it("refuses public relay hosts until the authenticated gateway exists", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "https://relay.example.com" });
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
expect(() =>
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
kind: "environment-port",
port: 5173,
}),
).toThrow(/authenticated preview gateway/);
});
it("normalizes schemeless localhost server-picker values", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://localhost:3773" });
const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
expect(resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), "localhost:5173")).toBe(
"http://localhost:5173/",
);
expect(
resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), "0.0.0.0:3000/app"),
).toBe("http://localhost:3000/app");
});
it("preserves localhost server-picker values when the prepared base is 127.0.0.1", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://127.0.0.1:3773" });
const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
expect(
resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), "localhost:5173/app?x=1#top"),
).toBe("http://localhost:5173/app?x=1#top");
});
it("normalizes public URLs without treating them as environment ports", async () => {
const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
expect(resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), "example.com/app")).toBe(
"https://example.com/app",
);
});
it("supports private IPv6 environment hosts", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://[::1]:3773" });
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
expect(
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
kind: "environment-port",
port: 5173,
path: "/app?mode=test",
}).resolvedUrl,
).toBe("http://[::1]:5173/app?mode=test");
});
it("leaves malformed input for the normal navigation error path", async () => {
const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
expect(resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), " ")).toBe(" ");
});
});
+105 -70
View File
@@ -1,92 +1,127 @@
import {
EnvironmentPortRouter,
type EnvironmentPortRouteRequest,
} from "@t3tools/client-runtime/preview";
import {
createRuntimeCommand,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type {
BrowserNavigationTarget,
EnvironmentId,
PreviewUrlResolution,
} from "@t3tools/contracts";
import { isLoopbackHost, normalizePreviewUrl } from "@t3tools/shared/preview";
import { normalizePreviewUrl } from "@t3tools/shared/preview";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Scope from "effect/Scope";
import { connectionAtomRuntime } from "~/connection/runtime";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { readPreparedConnection } from "~/state/session";
const isPrivateNetworkHost = (host: string): boolean => {
const normalized = host.toLowerCase().replace(/^\[|\]$/g, "");
if (normalized === "localhost" || normalized === "::1" || normalized.endsWith(".local")) {
return true;
}
if (normalized.endsWith(".ts.net")) return true;
const parts = normalized.split(".").map(Number);
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part))) return false;
return (
parts[0] === 10 ||
(parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) ||
(parts[0] === 192 && parts[1] === 168) ||
parts[0] === 127 ||
(parts[0] === 169 && parts[1] === 254)
);
};
interface AcquiredRoute {
readonly resolution: PreviewUrlResolution;
readonly scope: Scope.Closeable;
}
const isLocalLoopbackHost = (host: string): boolean => {
const normalized = host.toLowerCase().replace(/^\[|\]$/g, "");
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
};
export interface BrowserNavigationRoute {
readonly resolution: PreviewUrlResolution;
readonly commit: (tabId: string) => Promise<void>;
readonly release: () => Promise<void>;
}
export function resolveBrowserNavigationTarget(
const activeRoutes = new Map<string, Scope.Closeable>();
const closeRouteScope = (scope: Scope.Closeable): Promise<void> =>
Effect.runPromise(Scope.close(scope, Exit.void));
const acquireRouteCommand = createRuntimeCommand(connectionAtomRuntime, {
label: "preview route acquisition",
execute: ({ connection, target }: EnvironmentPortRouteRequest) =>
Effect.gen(function* () {
const scope = yield* Scope.make();
const resolution = yield* EnvironmentPortRouter.pipe(
Effect.flatMap((router) => router.acquire({ connection, target })),
Scope.provide(scope),
Effect.onError(() => Scope.close(scope, Exit.void)),
);
return { resolution, scope } satisfies AcquiredRoute;
}),
});
export async function acquireBrowserNavigationTarget(
environmentId: EnvironmentId,
target: BrowserNavigationTarget,
): PreviewUrlResolution {
if (target.kind === "url") {
return {
requestedUrl: target.url,
resolvedUrl: target.url,
resolutionKind: "direct",
environmentId,
};
}
): Promise<BrowserNavigationRoute> {
const connection = readPreparedConnection(environmentId);
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
const environmentUrl = new URL(connection.httpBaseUrl);
if (!isPrivateNetworkHost(environmentUrl.hostname)) {
throw new Error(
"This environment port needs the planned authenticated preview gateway; its server address is not directly private-network reachable.",
);
if (connection === null) {
throw new Error(`Environment ${environmentId} is not connected.`);
}
const protocol = target.protocol ?? "http";
const path = target.path?.startsWith("/") ? target.path : `/${target.path ?? ""}`;
const requestedUrl = `${protocol}://localhost:${target.port}${path}`;
const normalizedEnvironmentHost = environmentUrl.hostname.replace(/^\[|\]$/g, "");
const resolvedHost = normalizedEnvironmentHost.includes(":")
? `[${normalizedEnvironmentHost}]`
: normalizedEnvironmentHost;
const resolved = new URL(path, `${protocol}://${resolvedHost}:${target.port}`);
const result = await acquireRouteCommand.run(appAtomRegistry, { connection, target });
if (result._tag === "Failure") {
throw squashAtomCommandFailure(result);
}
const acquired = result.value;
let ownership: "pending" | "committed" | "released" = "pending";
return {
requestedUrl,
resolvedUrl: resolved.toString(),
resolutionKind:
normalizedEnvironmentHost === "localhost" || normalizedEnvironmentHost === "127.0.0.1"
? "direct"
: "direct-private-network",
environmentId,
resolution: acquired.resolution,
commit: async (tabId) => {
if (ownership !== "pending") return;
ownership = "committed";
const previous = activeRoutes.get(tabId);
if (acquired.resolution.resolutionKind === "ssh-forward") {
activeRoutes.set(tabId, acquired.scope);
} else {
activeRoutes.delete(tabId);
await closeRouteScope(acquired.scope);
}
if (previous !== undefined && previous !== acquired.scope) {
await closeRouteScope(previous);
}
},
release: async () => {
if (ownership !== "pending") return;
ownership = "released";
await closeRouteScope(acquired.scope);
},
};
}
export function resolveDiscoveredServerUrl(environmentId: EnvironmentId, rawUrl: string): string {
export async function acquireDiscoveredServerRoute(
environmentId: EnvironmentId,
rawUrl: string,
): Promise<BrowserNavigationRoute> {
let url = rawUrl;
try {
const normalizedUrl = normalizePreviewUrl(rawUrl);
const parsed = new URL(normalizedUrl);
if (!isLoopbackHost(parsed.hostname)) return normalizedUrl;
const connection = readPreparedConnection(environmentId);
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
const environmentUrl = new URL(connection.httpBaseUrl);
if (parsed.hostname !== "0.0.0.0" && isLocalLoopbackHost(environmentUrl.hostname)) {
return normalizedUrl;
}
const port = Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80));
return resolveBrowserNavigationTarget(environmentId, {
kind: "environment-port",
port,
protocol: parsed.protocol === "https:" ? "https" : "http",
path: `${parsed.pathname}${parsed.search}${parsed.hash}`,
}).resolvedUrl;
url = normalizePreviewUrl(rawUrl);
} catch {
return rawUrl;
// Keep malformed input on the preview's normal navigation error path.
}
return acquireBrowserNavigationTarget(environmentId, { kind: "url", url });
}
export async function releaseBrowserNavigationRoute(tabId: string): Promise<void> {
const scope = activeRoutes.get(tabId);
if (scope === undefined) return;
activeRoutes.delete(tabId);
await closeRouteScope(scope);
}
export async function withBrowserNavigationRoute<A>(
route: BrowserNavigationRoute | undefined,
use: () => Promise<A>,
): Promise<A> {
try {
return await use();
} finally {
await route?.release();
}
}
export async function resetBrowserNavigationRoutesForTests(): Promise<void> {
const scopes = [...activeRoutes.values()];
activeRoutes.clear();
await Promise.all(scopes.map(closeRouteScope));
}
+26 -2
View File
@@ -1,5 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
import { useEffect, type CSSProperties, type ReactNode } from "react";
import { useEffect, useState, type CSSProperties, type ReactNode } from "react";
import { useNavigate } from "@tanstack/react-router";
import { isElectron } from "../env";
@@ -55,11 +55,35 @@ function SidebarControl() {
export function AppSidebarLayout({ children }: { children: ReactNode }) {
const navigate = useNavigate();
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
return isMacosDesktop && typeof getWindowFullscreenState === "function"
? getWindowFullscreenState()
: false;
});
const macosWindowControlsStyle =
isElectron && isMacPlatform(navigator.platform)
isMacosDesktop && !isWindowFullscreen
? ({ "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET } as CSSProperties)
: undefined;
useEffect(() => {
if (!isMacosDesktop) return;
const bridge = window.desktopBridge;
if (!bridge) return;
const { getWindowFullscreenState, onWindowFullscreenStateChange } = bridge;
if (
typeof getWindowFullscreenState !== "function" ||
typeof onWindowFullscreenStateChange !== "function"
) {
return;
}
const unsubscribe = onWindowFullscreenStateChange(setIsWindowFullscreen);
setIsWindowFullscreen(getWindowFullscreenState());
return unsubscribe;
}, [isMacosDesktop]);
useEffect(() => {
const onMenuAction = window.desktopBridge?.onMenuAction;
if (typeof onMenuAction !== "function") {
+22 -5
View File
@@ -32,7 +32,7 @@ import React, {
useState,
type ReactNode,
} from "react";
import type { Components } from "react-markdown";
import type { Components, Options as ReactMarkdownOptions } from "react-markdown";
import ReactMarkdown from "react-markdown";
import { defaultUrlTransform } from "react-markdown";
import rehypeRaw from "rehype-raw";
@@ -60,6 +60,7 @@ import {
serializeTableElementToCsv,
serializeTableElementToMarkdown,
} from "../markdown-clipboard";
import { remarkNormalizeListItemIndentation } from "../markdown-list-indentation";
import {
normalizeMarkdownLinkDestination,
resolveMarkdownFileLinkMeta,
@@ -164,6 +165,24 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
},
} satisfies Parameters<typeof rehypeSanitize>[0];
const CHAT_MARKDOWN_REMARK_PLUGINS = [
remarkGfm,
remarkNormalizeListItemIndentation,
remarkPreserveCodeMeta,
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
remarkGfm,
remarkNormalizeListItemIndentation,
remarkBreaks,
remarkPreserveCodeMeta,
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
const CHAT_MARKDOWN_REHYPE_PLUGINS = [
rehypeRaw,
[rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
function extractFenceLanguage(className: string | undefined): string {
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
const raw = match?.[1] ?? "text";
@@ -1545,11 +1564,9 @@ function ChatMarkdown({
>
<ReactMarkdown
remarkPlugins={
lineBreaks
? [remarkGfm, remarkBreaks, remarkPreserveCodeMeta]
: [remarkGfm, remarkPreserveCodeMeta]
lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS
}
rehypePlugins={[rehypeRaw, [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA]]}
rehypePlugins={CHAT_MARKDOWN_REHYPE_PLUGINS}
components={markdownComponents}
urlTransform={markdownUrlTransform}
>
@@ -17,7 +17,7 @@ export function ConnectionStatusDot({
{pingClassName ? (
<span
className={cn(
"absolute inline-flex h-full w-full animate-ping rounded-full",
"absolute inline-flex h-full w-full animate-status-ping rounded-full",
pingClassName,
)}
/>
+2 -1
View File
@@ -1,4 +1,5 @@
import type { EnvironmentId } from "@t3tools/contracts";
import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon";
import { FolderIcon } from "lucide-react";
import { useState } from "react";
import { useAssetUrl } from "../assets/assetUrls";
@@ -15,7 +16,7 @@ export function ProjectFavicon(input: {
cwd: input.cwd,
});
if (!src) {
if (!src || isProjectFaviconFallbackUrl(src)) {
return <ProjectFaviconFallback className={input.className} />;
}
+6 -3
View File
@@ -771,7 +771,9 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
/>
}
>
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
<TerminalIcon
className={`size-3 ${terminalStatus.pulse ? "animate-status-pulse" : ""}`}
/>
</TooltipTrigger>
<TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
</Tooltip>
@@ -2226,7 +2228,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
<span className="absolute inset-0 flex items-center justify-center transition-opacity duration-150 group-hover/project-header:opacity-0">
<span
className={`size-[9px] rounded-full ${projectStatus.dotClass} ${
projectStatus.pulse ? "animate-pulse" : ""
projectStatus.pulse ? "animate-status-pulse" : ""
}`}
/>
</span>
@@ -3181,8 +3183,9 @@ export default function Sidebar() {
return buildPhysicalToLogicalProjectKeyMap({
projects: orderedProjects,
settings: projectGroupingSettings,
primaryEnvironmentId,
});
}, [orderedProjects, projectGroupingSettings]);
}, [orderedProjects, projectGroupingSettings, primaryEnvironmentId]);
const projectPhysicalKeyByScopedRef = useMemo(
() =>
new Map(
@@ -149,7 +149,7 @@ export function ThreadStatusLabel({
>
<span
className={`size-[9px] rounded-full ${status.dotClass} ${
status.pulse ? "animate-pulse" : ""
status.pulse ? "animate-status-pulse" : ""
}`}
/>
</TooltipTrigger>
@@ -170,7 +170,7 @@ export function ThreadStatusLabel({
>
<span
className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
status.pulse ? "animate-pulse" : ""
status.pulse ? "animate-status-pulse" : ""
}`}
/>
<span className="hidden md:inline">{status.label}</span>
@@ -276,7 +276,9 @@ export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSumma
/>
}
>
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
<TerminalIcon
className={`size-3 ${terminalStatus.pulse ? "animate-status-pulse" : ""}`}
/>
</TooltipTrigger>
<TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
</Tooltip>
@@ -1055,9 +1055,9 @@ function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "workin
<div className="py-0.5 pl-1.5">
<div className="flex items-center gap-2 pt-1 text-[11px] text-muted-foreground/70 tabular-nums">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-status-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-status-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-status-pulse [animation-delay:400ms]" />
</span>
<span>
{row.createdAt ? (
@@ -1,5 +1,6 @@
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import {
type EnvironmentConnectionPresentation,
RelayConnectionRegistration,
RelayConnectionTarget,
} from "@t3tools/client-runtime/connection";
@@ -10,7 +11,7 @@ import {
import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import * as Option from "effect/Option";
import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
import { type ReactNode, useCallback, useEffect, useState } from "react";
import { environmentCatalog } from "~/connection/catalog";
import { cn } from "~/lib/utils";
@@ -22,6 +23,12 @@ import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "../settings/itemRo
import { Button } from "../ui/button";
import { Skeleton } from "../ui/skeleton";
import { toastManager } from "../ui/toast";
import { presentSavedCloudEnvironmentConnection } from "./cloudEnvironmentConnectionPresentation";
export interface SavedCloudEnvironmentConnection {
readonly environmentId: EnvironmentId;
readonly connection: EnvironmentConnectionPresentation;
}
export function RemoteEnvironmentRowsSkeleton() {
return (
@@ -40,19 +47,19 @@ export function RemoteEnvironmentRowsSkeleton() {
/**
* The user's T3 Connect environments from relay discovery, each with a
* Connect button. The primary environment is always excluded; already-saved
* environments are hidden unless `showSavedAsConnected` renders them as
* connected instead (used by onboarding, where the full device mesh should be
* visible).
* environments are hidden unless `showSavedEnvironments` renders them with
* their live connection state (used by onboarding, where the full device mesh
* should be visible).
*/
export function CloudEnvironmentConnectRows({
primaryEnvironmentId,
savedEnvironmentIds,
showSavedAsConnected = false,
savedEnvironments,
showSavedEnvironments = false,
empty = null,
}: {
readonly primaryEnvironmentId: EnvironmentId | null;
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
readonly showSavedAsConnected?: boolean;
readonly savedEnvironments: ReadonlyArray<SavedCloudEnvironmentConnection>;
readonly showSavedEnvironments?: boolean;
readonly empty?: ReactNode;
}) {
const environmentsState = useRelayEnvironmentDiscovery();
@@ -77,7 +84,9 @@ export function CloudEnvironmentConnectRows({
const [connectingEnvironmentId, setConnectingEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const savedIds = useMemo(() => new Set(savedEnvironmentIds), [savedEnvironmentIds]);
const savedById = new Map(
savedEnvironments.map((environment) => [environment.environmentId, environment]),
);
useEffect(() => {
void refreshRelayEnvironments();
@@ -90,8 +99,8 @@ export function CloudEnvironmentConnectRows({
if (result._tag === "Success") {
toastManager.add({
type: "success",
title: "Environment connected",
description: `${environment.label} is available through T3 Connect.`,
title: "Environment added",
description: `Connecting to ${environment.label} through T3 Connect.`,
});
return;
}
@@ -121,10 +130,10 @@ export function CloudEnvironmentConnectRows({
const visibleEnvironments = [...environmentsState.environments.values()].filter(
({ environment }) =>
environment.environmentId !== primaryEnvironmentId &&
(showSavedAsConnected || !savedIds.has(environment.environmentId)),
(showSavedEnvironments || !savedById.has(environment.environmentId)),
);
const standalone = showSavedAsConnected || savedEnvironmentIds.length === 0;
const standalone = showSavedEnvironments || savedEnvironments.length === 0;
if (
standalone &&
@@ -163,31 +172,57 @@ export function CloudEnvironmentConnectRows({
}
return visibleEnvironments.map(({ environment, availability, error }) => {
const alreadyConnected = savedIds.has(environment.environmentId);
const savedEnvironment = savedById.get(environment.environmentId);
const savedConnection = savedEnvironment
? presentSavedCloudEnvironmentConnection(savedEnvironment.connection)
: null;
const dotClassName = savedConnection
? savedConnection.tone === "connected"
? "bg-success"
: savedConnection.tone === "connecting"
? "bg-warning"
: savedConnection.tone === "error"
? "bg-destructive"
: "bg-muted-foreground/35"
: availability === "online"
? "bg-success"
: availability === "error"
? "bg-destructive"
: availability === "checking"
? "bg-warning"
: "bg-muted-foreground/35";
const statusText = savedConnection
? savedConnection.statusText
: availability === "online"
? "Available · Relay online"
: availability === "offline"
? "Available · Relay offline"
: availability === "checking"
? "Available · Checking relay status…"
: (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable");
return (
<div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0">
<div className="flex items-center gap-2">
<ConnectionStatusDot
dotClassName={
availability === "online"
? "bg-success"
: availability === "error"
? "bg-destructive"
: availability === "checking"
? "bg-warning"
: "bg-muted-foreground/35"
dotClassName={dotClassName}
pingClassName={
savedConnection?.tone === "connecting" ||
(savedConnection === null && availability === "checking")
? "bg-warning/60 duration-2000"
: null
}
pingClassName={availability === "checking" ? "bg-warning/60 duration-2000" : null}
tooltipText={
availability === "online"
? "Relay online"
: availability === "offline"
? "Relay offline"
: availability === "checking"
? "Checking relay status"
: (Option.getOrNull(error)?.message ?? "Relay status unavailable")
savedConnection
? savedConnection.statusText
: availability === "online"
? "Relay online"
: availability === "offline"
? "Relay offline"
: availability === "checking"
? "Checking relay status"
: (Option.getOrNull(error)?.message ?? "Relay status unavailable")
}
/>
<p className="truncate text-sm font-medium">{environment.label}</p>
@@ -195,21 +230,19 @@ export function CloudEnvironmentConnectRows({
<p
className={cn(
"mt-1 truncate text-xs",
availability === "error" ? "text-destructive" : "text-muted-foreground",
savedConnection?.tone === "error" ||
(savedConnection?.tone === "connecting" && savedEnvironment?.connection.error) ||
(savedConnection === null && availability === "error")
? "text-destructive"
: "text-muted-foreground",
)}
>
{availability === "online"
? "Available · Relay online"
: availability === "offline"
? "Available · Relay offline"
: availability === "checking"
? "Available · Checking relay status…"
: (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable")}
{statusText}
</p>
</div>
{alreadyConnected ? (
{savedConnection ? (
<Button size="sm" variant="outline" disabled>
Connected
{savedConnection.buttonLabel}
</Button>
) : (
<Button
@@ -1,7 +1,7 @@
import { useAuth } from "@clerk/react";
import { AuthAdministrativeScopes, AuthRelayWriteScope } from "@t3tools/contracts";
import { CheckIcon } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useEffect, useRef, useState } from "react";
import {
CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
@@ -411,20 +411,16 @@ function OnboardingToggleRow({
function DevicesStep() {
const { environments } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
const savedEnvironmentIds = useMemo(
() =>
environments
.filter((environment) => environment.entry.target._tag !== "PrimaryConnectionTarget")
.map((environment) => environment.environmentId),
[environments],
const savedEnvironments = environments.filter(
(environment) => environment.entry.target._tag !== "PrimaryConnectionTarget",
);
return (
<div className="overflow-hidden rounded-lg border">
<CloudEnvironmentConnectRows
primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}
savedEnvironmentIds={savedEnvironmentIds}
showSavedAsConnected
savedEnvironments={savedEnvironments}
showSavedEnvironments
empty={
<p className="px-4 py-6 text-center text-sm text-muted-foreground">
No other environments are published to your account yet. Publish one from another device
@@ -0,0 +1,55 @@
import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
import { describe, expect, it } from "vite-plus/test";
import { presentSavedCloudEnvironmentConnection } from "./cloudEnvironmentConnectionPresentation";
function connection(
phase: EnvironmentConnectionPresentation["phase"],
error: string | null = null,
): EnvironmentConnectionPresentation {
return { phase, error, traceId: null };
}
describe("saved cloud environment connection presentation", () => {
it("only labels a live connection as connected", () => {
expect(presentSavedCloudEnvironmentConnection(connection("connected"))).toEqual({
buttonLabel: "Connected",
statusText: "Connected",
tone: "connected",
});
expect(presentSavedCloudEnvironmentConnection(connection("connecting"))).toEqual({
buttonLabel: "Connecting…",
statusText: "Connecting...",
tone: "connecting",
});
});
it("surfaces a failed attempt while the supervisor reconnects", () => {
expect(
presentSavedCloudEnvironmentConnection(
connection("reconnecting", "Relay environment endpoint is unavailable."),
),
).toEqual({
buttonLabel: "Reconnecting…",
statusText:
"Failed to connect. Reconnecting... Reason: Relay environment endpoint is unavailable.",
tone: "connecting",
});
});
it.each([
["error", "Connection failed", "Connection failed. Reason: Access denied.", "error"],
["offline", "Offline", "Offline", "idle"],
["available", "Not connected", "Available", "idle"],
] as const)(
"presents %s without claiming the environment is connected",
(phase, buttonLabel, statusText, tone) => {
expect(
presentSavedCloudEnvironmentConnection(
connection(phase, phase === "error" ? "Access denied." : null),
),
).toEqual({ buttonLabel, statusText, tone });
},
);
});
@@ -0,0 +1,58 @@
import {
connectionStatusText,
type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection";
export interface SavedCloudEnvironmentConnectionPresentation {
readonly buttonLabel: string;
readonly statusText: string;
readonly tone: "connected" | "connecting" | "error" | "idle";
}
/**
* Present the live supervisor state for an environment that is already in the
* connection catalog. Catalog membership only means the environment is saved;
* it does not mean the connection attempt succeeded.
*/
export function presentSavedCloudEnvironmentConnection(
connection: EnvironmentConnectionPresentation,
): SavedCloudEnvironmentConnectionPresentation {
switch (connection.phase) {
case "connected":
return {
buttonLabel: "Connected",
statusText: connectionStatusText(connection),
tone: "connected",
};
case "connecting":
return {
buttonLabel: "Connecting…",
statusText: connectionStatusText(connection),
tone: "connecting",
};
case "reconnecting":
return {
buttonLabel: "Reconnecting…",
statusText: connectionStatusText(connection),
tone: "connecting",
};
case "error":
return {
buttonLabel: "Connection failed",
statusText: connectionStatusText(connection),
tone: "error",
};
case "offline":
return {
buttonLabel: "Offline",
statusText: connectionStatusText(connection),
tone: "idle",
};
case "available":
return {
buttonLabel: "Not connected",
statusText: connectionStatusText(connection),
tone: "idle",
};
}
}
@@ -66,7 +66,7 @@ function AgentBrowserCursorEvent(props: {
{event.phase === "click" ? (
<span
key={event.sequence}
className="absolute left-0.5 top-0.5 size-4 animate-ping rounded-full bg-primary/25 motion-reduce:animate-none"
className="absolute left-0.5 top-0.5 size-4 animate-status-ping rounded-full bg-primary/25 motion-reduce:animate-none"
/>
) : null}
<MousePointer2
@@ -28,7 +28,10 @@ import {
updatePreviewServerSnapshot,
} from "~/previewStateStore";
import { useRightPanelStore } from "~/rightPanelStore";
import { resolveBrowserNavigationTarget } from "~/browser/browserTargetResolver";
import {
acquireBrowserNavigationTarget,
withBrowserNavigationRoute,
} from "~/browser/browserTargetResolver";
import {
readActiveBrowserRecordingTabId,
startBrowserRecording,
@@ -343,79 +346,89 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
return await currentStatus(threadRef, tabId);
case "open": {
const input = request.input as PreviewAutomationOpenInput;
let activeTabId = resolvePreviewAutomationOpenTab(
state,
request.tabId,
input.reuseExistingTab ?? true,
);
let activeSnapshot = activeTabId
? (state.sessions[activeTabId] ?? state.snapshot ?? undefined)
const route = input.url
? await acquireBrowserNavigationTarget(environmentId, {
kind: "url",
url: input.url,
})
: undefined;
const reusedExistingTab = activeTabId !== null;
tabId = activeTabId;
if (!activeTabId) {
const result = await open({
environmentId,
input: {
threadId: request.threadId,
...(input.url ? { url: input.url } : {}),
},
});
if (result._tag === "Failure") {
return raiseAtomCommandFailure(result);
}
const snapshot = result.value;
applyPreviewServerSnapshot(threadRef, snapshot);
activeTabId = snapshot.tabId;
activeSnapshot = snapshot;
const resolvedInputUrl = route?.resolution.resolvedUrl;
return await withBrowserNavigationRoute(route, async () => {
let activeTabId = resolvePreviewAutomationOpenTab(
state,
request.tabId,
input.reuseExistingTab ?? true,
);
let activeSnapshot = activeTabId
? (state.sessions[activeTabId] ?? state.snapshot ?? undefined)
: undefined;
const reusedExistingTab = activeTabId !== null;
tabId = activeTabId;
}
if (input.show ?? true) {
useRightPanelStore.getState().openBrowser(threadRef, activeTabId);
}
if (activeSnapshot && previewAutomationOpenNeedsOverlay(input, activeSnapshot)) {
await waitForDesktopOverlay(
threadRef,
request.requestId,
activeTabId,
request.timeoutMs,
);
}
if (reusedExistingTab && input.url && previewBridge) {
const resolution = resolveBrowserNavigationTarget(environmentId, {
kind: "url",
url: input.url,
});
await previewBridge.navigate(activeTabId, resolution.resolvedUrl);
await waitForNavigationReadiness(
threadRef,
request.requestId,
activeTabId,
"load",
request.timeoutMs,
);
}
return await currentStatus(threadRef, activeTabId);
if (!activeTabId) {
const result = await open({
environmentId,
input: {
threadId: request.threadId,
...(resolvedInputUrl ? { url: resolvedInputUrl } : {}),
},
});
if (result._tag === "Failure") {
return raiseAtomCommandFailure(result);
}
const snapshot = result.value;
applyPreviewServerSnapshot(threadRef, snapshot);
activeTabId = snapshot.tabId;
activeSnapshot = snapshot;
tabId = activeTabId;
await route?.commit(activeTabId);
}
if (input.show ?? true) {
useRightPanelStore.getState().openBrowser(threadRef, activeTabId);
}
if (activeSnapshot && previewAutomationOpenNeedsOverlay(input, activeSnapshot)) {
await waitForDesktopOverlay(
threadRef,
request.requestId,
activeTabId,
request.timeoutMs,
);
}
if (reusedExistingTab && resolvedInputUrl && previewBridge) {
await previewBridge.navigate(activeTabId, resolvedInputUrl);
await route?.commit(activeTabId);
await waitForNavigationReadiness(
threadRef,
request.requestId,
activeTabId,
"load",
request.timeoutMs,
);
}
return await currentStatus(threadRef, activeTabId);
});
}
case "navigate": {
const ready = await requireReadyTab();
const input = request.input as PreviewAutomationNavigateInput;
const resolution = resolveBrowserNavigationTarget(
const route = await acquireBrowserNavigationTarget(
environmentId,
input.target ?? {
kind: "url",
url: input.url!,
},
);
await ready.bridge.navigate(ready.tabId, resolution.resolvedUrl);
await waitForNavigationReadiness(
threadRef,
request.requestId,
ready.tabId,
input.readiness ?? "load",
input.timeoutMs ?? request.timeoutMs,
);
return await currentStatus(threadRef, ready.tabId);
return await withBrowserNavigationRoute(route, async () => {
await ready.bridge.navigate(ready.tabId, route.resolution.resolvedUrl);
await route.commit(ready.tabId);
await waitForNavigationReadiness(
threadRef,
request.requestId,
ready.tabId,
input.readiness ?? "load",
input.timeoutMs ?? request.timeoutMs,
);
return await currentStatus(threadRef, ready.tabId);
});
}
case "resize": {
const ready = await requireReadyTab();
@@ -266,7 +266,7 @@ export function PreviewChromeRow({
>
<Camera className={cn(recording && "text-destructive")} />
{recording ? (
<span className="absolute right-0.5 top-0.5 size-1.5 animate-pulse rounded-full bg-destructive" />
<span className="absolute right-0.5 top-0.5 size-1.5 animate-status-pulse rounded-full bg-destructive" />
) : null}
</TooltipTrigger>
<TooltipPopup>
@@ -36,7 +36,7 @@ function describeServer(server: PreviewableServer): string {
function PulsingDot() {
return (
<span aria-label="Listening" className="relative inline-flex size-2 shrink-0">
<span className="absolute inset-0 animate-ping rounded-full bg-success opacity-60" />
<span className="absolute inset-0 animate-status-ping rounded-full bg-success opacity-60" />
<span className="relative inline-flex size-2 rounded-full bg-success" />
</span>
);
+24 -14
View File
@@ -17,7 +17,10 @@ import {
updatePreviewServerSnapshot,
useThreadPreviewState,
} from "~/previewStateStore";
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
import {
acquireDiscoveredServerRoute,
withBrowserNavigationRoute,
} from "~/browser/browserTargetResolver";
import { useEnvironment, useEnvironmentHttpBaseUrl } from "~/state/environments";
import { previewEnvironment } from "~/state/preview";
import { useAtomCommand } from "~/state/use-atom-command";
@@ -115,19 +118,26 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
const handleSubmitUrl = useCallback(
async (next: string) => {
try {
const resolvedUrl = resolveDiscoveredServerUrl(threadRef.environmentId, next);
if (tabId && previewBridge) {
// Drive the webview imperatively; `usePreviewBridge` mirrors the
// resolved URL back to the server so other clients stay in sync.
await previewBridge.navigate(tabId, resolvedUrl);
rememberPreviewUrl(threadRef, resolvedUrl);
} else {
await openPreviewSession({
openPreview: open,
threadRef,
url: resolvedUrl,
});
}
const route = await acquireDiscoveredServerRoute(threadRef.environmentId, next);
await withBrowserNavigationRoute(route, async () => {
const resolvedUrl = route.resolution.resolvedUrl;
if (tabId && previewBridge) {
// Drive the webview imperatively; `usePreviewBridge` mirrors the
// resolved URL back to the server so other clients stay in sync.
await previewBridge.navigate(tabId, resolvedUrl);
rememberPreviewUrl(threadRef, resolvedUrl);
await route.commit(tabId);
} else {
const result = await openPreviewSession({
openPreview: open,
threadRef,
url: resolvedUrl,
});
if (result._tag === "Success") {
await route.commit(result.value.tabId);
}
}
});
} catch {
// Server-side `failed` event renders the unreachable view.
}
@@ -7,6 +7,10 @@ import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const releaseBrowserNavigationRoute = vi.hoisted(() => vi.fn(async () => undefined));
vi.mock("~/browser/browserTargetResolver", () => ({ releaseBrowserNavigationRoute }));
import {
applyPreviewServerSnapshot,
readThreadPreviewState,
@@ -33,7 +37,10 @@ const snapshot: PreviewSessionSnapshot = {
updatedAt: "2026-06-18T19:00:00.000Z",
};
beforeEach(resetPreviewStateForTests);
beforeEach(() => {
resetPreviewStateForTests();
releaseBrowserNavigationRoute.mockClear();
});
describe("closePreviewSession", () => {
it("suppresses stale server snapshots while the close is in flight", async () => {
@@ -60,6 +67,7 @@ describe("closePreviewSession", () => {
finishClose?.();
await closing;
expect(closePreview).toHaveBeenCalledWith({ threadId: "thread-1", tabId: "tab-1" });
expect(releaseBrowserNavigationRoute).toHaveBeenCalledWith("tab-1");
});
it("restores the last snapshot when the server close fails", async () => {
@@ -75,5 +83,6 @@ describe("closePreviewSession", () => {
expect(result._tag).toBe("Failure");
expect(readThreadPreviewState(threadRef).snapshot).toEqual(snapshot);
expect(readThreadPreviewState(threadRef).sessions).toEqual({ [snapshot.tabId]: snapshot });
expect(releaseBrowserNavigationRoute).not.toHaveBeenCalled();
});
});
@@ -7,6 +7,7 @@ import type {
} from "@t3tools/contracts";
import { beginPreviewSessionClose, cancelPreviewSessionClose } from "~/previewStateStore";
import { releaseBrowserNavigationRoute } from "~/browser/browserTargetResolver";
interface ClosePreviewSessionInput<E> {
readonly closePreview: (input: {
@@ -32,6 +33,8 @@ export async function closePreviewSession<E>(
});
if (result._tag === "Failure") {
cancelPreviewSessionClose(input.threadRef, input.snapshot, input.tabId);
} else {
await releaseBrowserNavigationRoute(input.tabId);
}
return result;
}
@@ -0,0 +1,94 @@
import type { PreviewSessionSnapshot, ScopedThreadRef } from "@t3tools/contracts";
import { AsyncResult } from "effect/unstable/reactivity";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const mocks = vi.hoisted(() => ({
acquireDiscoveredServerRoute: vi.fn(),
commit: vi.fn(async () => undefined),
release: vi.fn(async () => undefined),
openBrowser: vi.fn(),
openPreviewSession: vi.fn(),
}));
vi.mock("~/browser/browserTargetResolver", () => ({
acquireDiscoveredServerRoute: mocks.acquireDiscoveredServerRoute,
}));
vi.mock("~/rightPanelStore", () => ({
useRightPanelStore: { getState: () => ({ openBrowser: mocks.openBrowser }) },
}));
vi.mock("./openPreviewSession", () => ({ openPreviewSession: mocks.openPreviewSession }));
import { openDiscoveredPort } from "./openDiscoveredPort";
const threadRef = {
environmentId: "environment-1",
threadId: "thread-1",
} as ScopedThreadRef;
const snapshot = {
threadId: threadRef.threadId,
tabId: "tab-1",
navStatus: { _tag: "Success", url: "http://127.0.0.1:42173/", title: "App" },
canGoBack: false,
canGoForward: false,
updatedAt: "2026-07-16T00:00:00.000Z",
} satisfies PreviewSessionSnapshot;
describe("openDiscoveredPort", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.acquireDiscoveredServerRoute.mockResolvedValue({
resolution: { resolvedUrl: "http://127.0.0.1:42173/" },
commit: mocks.commit,
release: mocks.release,
});
mocks.openPreviewSession.mockResolvedValue(AsyncResult.success(snapshot));
});
it("holds the route through preview creation and transfers it to the new tab", async () => {
const result = await openDiscoveredPort({
threadRef,
port: {
host: "localhost",
port: 5173,
url: "http://localhost:5173/",
processName: null,
pid: null,
terminal: null,
},
openPreview: vi.fn(),
});
expect(result._tag).toBe("Success");
expect(mocks.acquireDiscoveredServerRoute).toHaveBeenCalledWith(
threadRef.environmentId,
"http://localhost:5173/",
);
expect(mocks.openPreviewSession).toHaveBeenCalledWith(
expect.objectContaining({ url: "http://127.0.0.1:42173/" }),
);
expect(mocks.commit).toHaveBeenCalledWith("tab-1");
expect(mocks.release).toHaveBeenCalledOnce();
expect(mocks.openBrowser).toHaveBeenCalledWith(threadRef, "tab-1");
});
it("reports route acquisition failures as command failures", async () => {
mocks.acquireDiscoveredServerRoute.mockRejectedValueOnce(new Error("forward failed"));
const result = await openDiscoveredPort({
threadRef,
port: {
host: "localhost",
port: 5173,
url: "http://localhost:5173/",
processName: null,
pid: null,
terminal: null,
},
openPreview: vi.fn(),
});
expect(result._tag).toBe("Failure");
expect(mocks.openPreviewSession).not.toHaveBeenCalled();
});
});
@@ -3,8 +3,10 @@ import {
mapAtomCommandResult,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
import { acquireDiscoveredServerRoute } from "~/browser/browserTargetResolver";
import type { OpenPreviewMutation } from "~/browser/openFileInPreview";
import { useRightPanelStore } from "~/rightPanelStore";
import { openPreviewSession } from "./openPreviewSession";
@@ -14,13 +16,24 @@ export async function openDiscoveredPort<E>(input: {
readonly port: DiscoveredLocalServer;
readonly openPreview: OpenPreviewMutation<E>;
}): Promise<AtomCommandResult<void, E>> {
const resolvedUrl = resolveDiscoveredServerUrl(input.threadRef.environmentId, input.port.url);
const result = await openPreviewSession({
openPreview: input.openPreview,
threadRef: input.threadRef,
url: resolvedUrl,
});
return mapAtomCommandResult(result, (snapshot) => {
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
});
try {
const route = await acquireDiscoveredServerRoute(input.threadRef.environmentId, input.port.url);
try {
const result = await openPreviewSession({
openPreview: input.openPreview,
threadRef: input.threadRef,
url: route.resolution.resolvedUrl,
});
if (result._tag === "Success") {
await route.commit(result.value.tabId);
}
return mapAtomCommandResult(result, (snapshot) => {
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
});
} finally {
await route.release();
}
} catch (cause) {
return AsyncResult.failure(Cause.die(cause));
}
}
@@ -3,7 +3,6 @@ import { isLoopbackHost } from "@t3tools/shared/preview";
import { useMemo } from "react";
import type { EnvironmentId } from "@t3tools/contracts";
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
import { useDiscoveredPorts } from "~/portDiscoveryState";
export interface PreviewableServer extends DiscoveredLocalServer {
@@ -33,10 +32,7 @@ export function useDiscoveredLocalServers(
return useMemo(
() =>
mergeServers({
scanner: scannerSnapshot.map((server) => ({
...server,
url: resolveDiscoveredServerUrl(input.environmentId, server.url),
})),
scanner: scannerSnapshot,
configuredUrls: input.configuredUrls ?? [],
recentlySeenUrls: input.recentlySeenUrls ?? [],
}),
@@ -1672,18 +1672,18 @@ function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnable
function CloudRemoteEnvironmentRows({
primaryEnvironmentId,
savedEnvironmentIds,
savedEnvironments,
}: {
readonly primaryEnvironmentId: EnvironmentId | null;
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
readonly savedEnvironments: ReadonlyArray<EnvironmentPresentation>;
}) {
return hasCloudPublicConfig() ? (
<CloudEnvironmentConnectRows
primaryEnvironmentId={primaryEnvironmentId}
savedEnvironmentIds={savedEnvironmentIds}
savedEnvironments={savedEnvironments}
empty={<EmptyRemoteEnvironments />}
/>
) : savedEnvironmentIds.length === 0 ? (
) : savedEnvironments.length === 0 ? (
<EmptyRemoteEnvironments cloudEnabled={false} />
) : null;
}
@@ -1713,10 +1713,6 @@ export function ConnectionsSettings() {
.toSorted((left, right) => left.label.localeCompare(right.label)),
[environments],
);
const savedEnvironmentIds = useMemo(
() => savedEnvironments.map((environment) => environment.environmentId),
[savedEnvironments],
);
const savedDesktopSshEnvironmentsByAlias = useMemo(
() =>
savedEnvironments.reduce<Record<string, EnvironmentPresentation>>(
@@ -3363,7 +3359,7 @@ export function ConnectionsSettings() {
))}
<CloudRemoteEnvironmentRows
primaryEnvironmentId={primaryEnvironmentId}
savedEnvironmentIds={savedEnvironmentIds}
savedEnvironments={savedEnvironments}
/>
</SettingsSection>
</SettingsPageContainer>
+4 -4
View File
@@ -216,7 +216,7 @@ function Sidebar({
<SidebarInstanceContext value={instanceContextValue}>
<div
className={cn(
"flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",
"flex h-full w-(--sidebar-width) flex-col bg-sidebar surface-grain text-sidebar-foreground",
className,
)}
data-slot="sidebar"
@@ -234,7 +234,7 @@ function Sidebar({
<Sheet onOpenChange={setOpenMobile} open={openMobile} {...props}>
<SheetPopup
className={cn(
"w-(--sidebar-width) max-w-none bg-sidebar p-0 text-sidebar-foreground",
"w-(--sidebar-width) max-w-none bg-sidebar surface-grain p-0 text-sidebar-foreground",
className,
)}
data-mobile="true"
@@ -304,7 +304,7 @@ function Sidebar({
{...props}
>
<div
className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow-sm/5"
className="flex h-full w-full flex-col bg-sidebar surface-grain group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow-sm/5"
data-sidebar="sidebar"
data-slot="sidebar-inner"
>
@@ -622,7 +622,7 @@ function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
return (
<main
className={cn(
"relative flex min-w-0 w-full flex-1 flex-col bg-background",
"relative flex min-w-0 w-full flex-1 flex-col bg-background surface-grain",
"md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ms-2 md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ms-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm/5",
className,
)}
+28
View File
@@ -272,6 +272,34 @@ const capabilitiesLayer = Layer.effectContext(
}),
});
}),
forwardPort: Effect.fn("web.connectionPlatform.ssh.forwardPort")(function* (input) {
const bridge = window.desktopBridge;
if (bridge === undefined) {
return yield* new ConnectionBlockedError({
reason: "unsupported",
detail: "SSH port forwarding is only available in the desktop app.",
});
}
const lease = yield* Effect.acquireRelease(
Effect.tryPromise({
try: () => bridge.acquireSshPortForward(input.target, input.remotePort),
catch: sshPreparationError,
}),
(acquired) =>
Effect.tryPromise(() => bridge.releaseSshPortForward(acquired.leaseId)).pipe(
Effect.catch((cause) =>
Effect.logWarning("Could not release SSH preview port forward.").pipe(
Effect.annotateLogs({
leaseId: acquired.leaseId,
remotePort: acquired.remotePort,
cause,
}),
),
),
),
);
return { localPort: lease.localPort };
}),
});
return Context.make(CloudSession, cloudSession).pipe(
+121
View File
@@ -7,6 +7,10 @@ import {
derivePhysicalProjectKey,
resolveProjectGroupingMode,
} from "./logicalProject";
import {
buildPhysicalToLogicalProjectKeyMap,
buildSidebarProjectSnapshots,
} from "./sidebarProjectGrouping";
import type { Project } from "./types";
const primaryEnvironmentId = EnvironmentId.make("env-primary");
@@ -119,4 +123,121 @@ describe("environment grouping", () => {
}),
).toBe("separate");
});
it("dedupes stale project rows with the same environment and workspace path", () => {
const duplicate = makeProject({
id: ProjectId.make("project-duplicate"),
workspaceRoot: "/tmp/shared-repo/",
repositoryIdentity,
updatedAt: "2026-01-01T00:00:00.000Z",
});
const primary = makeProject({
id: ProjectId.make("project-primary"),
repositoryIdentity,
updatedAt: "2026-01-02T00:00:00.000Z",
});
const remote = makeProject({
id: ProjectId.make("project-remote"),
environmentId: remoteEnvironmentId,
workspaceRoot: "/tmp/shared-repo",
repositoryIdentity,
});
const snapshots = buildSidebarProjectSnapshots({
projects: [primary, duplicate, remote],
settings: defaultGroupingSettings,
primaryEnvironmentId,
resolveEnvironmentLabel: (environmentId) =>
environmentId === remoteEnvironmentId ? "remote" : "primary",
});
expect(snapshots).toHaveLength(1);
expect(snapshots[0]?.groupedProjectCount).toBe(2);
expect(snapshots[0]?.memberProjects.map((project) => project.id)).toEqual([
primary.id,
remote.id,
]);
});
it("prefers the fresher project row when duplicate stale rows are ordered first", () => {
const staleDuplicate = makeProject({
id: ProjectId.make("project-stale"),
workspaceRoot: "/tmp/shared-repo/",
repositoryIdentity,
updatedAt: "2026-01-01T00:00:00.000Z",
});
const canonical = makeProject({
id: ProjectId.make("project-canonical"),
workspaceRoot: "/tmp/shared-repo",
repositoryIdentity,
updatedAt: "2026-01-02T00:00:00.000Z",
});
const snapshots = buildSidebarProjectSnapshots({
projects: [staleDuplicate, canonical],
settings: defaultGroupingSettings,
primaryEnvironmentId,
resolveEnvironmentLabel: () => "primary",
});
expect(snapshots).toHaveLength(1);
expect(snapshots[0]?.memberProjects.map((project) => project.id)).toEqual([canonical.id]);
expect(snapshots[0]?.id).toBe(canonical.id);
});
it("dedupes stale project rows before logical grouping", () => {
const staleWithoutRepositoryIdentity = makeProject({
id: ProjectId.make("project-stale"),
repositoryIdentity: null,
updatedAt: "2026-01-01T00:00:00.000Z",
});
const canonical = makeProject({
id: ProjectId.make("project-canonical"),
repositoryIdentity,
updatedAt: "2026-01-02T00:00:00.000Z",
});
const remote = makeProject({
id: ProjectId.make("project-remote"),
environmentId: remoteEnvironmentId,
repositoryIdentity,
});
const snapshots = buildSidebarProjectSnapshots({
projects: [staleWithoutRepositoryIdentity, canonical, remote],
settings: defaultGroupingSettings,
primaryEnvironmentId,
resolveEnvironmentLabel: (environmentId) =>
environmentId === remoteEnvironmentId ? "remote" : "primary",
});
expect(snapshots).toHaveLength(1);
expect(snapshots[0]?.projectKey).toBe(repositoryIdentity.canonicalKey);
expect(snapshots[0]?.memberProjects.map((project) => project.id)).toEqual([
canonical.id,
remote.id,
]);
});
it("routes duplicate physical project keys to the winning logical group", () => {
const staleWithoutRepositoryIdentity = makeProject({
id: ProjectId.make("project-stale"),
repositoryIdentity: null,
updatedAt: "2026-01-01T00:00:00.000Z",
});
const canonical = makeProject({
id: ProjectId.make("project-canonical"),
repositoryIdentity,
updatedAt: "2026-01-02T00:00:00.000Z",
});
const physicalToLogicalKey = buildPhysicalToLogicalProjectKeyMap({
projects: [staleWithoutRepositoryIdentity, canonical],
settings: defaultGroupingSettings,
primaryEnvironmentId,
});
expect(physicalToLogicalKey.get(derivePhysicalProjectKey(staleWithoutRepositoryIdentity))).toBe(
repositoryIdentity.canonicalKey,
);
});
});
+76 -13
View File
@@ -36,6 +36,11 @@
@theme inline {
--animate-skeleton: skeleton 2s -1s infinite linear;
/* Duty-cycled indicator animations: long opacity holds with short stepped
ramps, so the compositor only produces frames while the value changes
(~20% of the cycle) instead of every vsync. Keep flat holds dominant. */
--animate-status-pulse: status-pulse 2s infinite;
--animate-status-ping: status-ping 2s infinite;
--font-sans:
"DM Sans Variable", "DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui,
sans-serif;
@@ -78,6 +83,36 @@
background-position: -200% 0;
}
}
@keyframes status-pulse {
0%,
40% {
opacity: 1;
animation-timing-function: steps(6);
}
50%,
90% {
opacity: 0.5;
animation-timing-function: steps(6);
}
100% {
opacity: 1;
}
}
@keyframes status-ping {
/* Burst first (immediate feedback for click ripples), then hold
invisible for the rest of the cycle. Mirrors animate-ping's
75%-scale start. */
0% {
opacity: 0.9;
scale: 0.75;
animation-timing-function: steps(8);
}
40%,
100% {
opacity: 0;
scale: 2;
}
}
}
@layer base {
@@ -151,11 +186,18 @@
padding-inline-end: calc(env(safe-area-inset-right) + 0.75rem);
}
.chat-composer-glass,
.chat-composer-lower-chrome {
.chat-composer-glass {
background: color-mix(in srgb, var(--card) 20%, transparent);
}
/* Mix from --background (not --card): the lower chrome is a full-width
strip over the main view, and a card-tinted wash reads as a lighter
seam against it when no content is scrolled underneath. The backdrop
blur, not the tint, carries the frosted effect. */
.chat-composer-lower-chrome {
background: color-mix(in srgb, var(--background) 20%, transparent);
}
.chat-composer-glass {
box-shadow:
0 18px 48px -20px rgb(0 0 0 / 28%),
@@ -167,11 +209,14 @@
backdrop-filter: blur(16px);
}
.dark .chat-composer-glass,
.dark .chat-composer-lower-chrome {
.dark .chat-composer-glass {
background: color-mix(in srgb, var(--card) 45%, transparent);
}
.dark .chat-composer-lower-chrome {
background: color-mix(in srgb, var(--background) 45%, transparent);
}
.dark .chat-composer-glass {
box-shadow:
0 18px 48px -20px rgb(0 0 0 / 60%),
@@ -192,10 +237,13 @@
}
@supports not ((-webkit-backdrop-filter: blur(1px)) or (backdrop-filter: blur(1px))) {
.chat-composer-glass,
.chat-composer-lower-chrome {
.chat-composer-glass {
background: var(--card);
}
.chat-composer-lower-chrome {
background: var(--background);
}
}
}
@@ -215,6 +263,15 @@
padding-right: max(env(safe-area-inset-right), 0px);
}
/* Grain texture for chrome surfaces that float above the body (see the
--surface-grain note). Layered over the element's background-color, so it
composes with bg-* utilities. */
@utility surface-grain {
background-image: var(--surface-grain);
background-repeat: repeat;
background-size: 256px 256px;
}
/* Suppress all transitions during theme changes */
.no-transitions,
.no-transitions *,
@@ -320,13 +377,19 @@ body {
padding-top: max(env(safe-area-inset-top), 0px);
}
body::after {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
opacity: 0.035;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
/* App-chrome grain. Baked into each surface's own background (behind
content) rather than a fixed overlay on top: a full-viewport overlay
forces the compositor to re-blend every frame any animation produces,
which multiplied idle GPU cost. The overlay's 0.035 opacity lives in the
SVG rect instead. Surfaces that float over the body (e.g. the inset main
card) must opt in via the surface-grain utility, or they lose the
grain's subtle brightening and stand out against the body. */
:root {
--surface-grain: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='0.035'/%3E%3C/svg%3E");
}
body {
background-image: var(--surface-grain);
background-repeat: repeat;
background-size: 256px 256px;
}
@@ -0,0 +1,82 @@
import { renderToStaticMarkup } from "react-dom/server";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { describe, expect, it } from "vite-plus/test";
import { remarkNormalizeListItemIndentation } from "./markdown-list-indentation";
function renderMarkdown(markdown: string): string {
return renderToStaticMarkup(
<ReactMarkdown remarkPlugins={[remarkGfm, remarkNormalizeListItemIndentation]}>
{markdown}
</ReactMarkdown>,
);
}
describe("remarkNormalizeListItemIndentation", () => {
it("renders same-line over-indented list content as list text", () => {
const html = renderMarkdown(`why did you do this?
- for (const step of rest.steps) {
- if (step.request.body) {
- step.request.body = "<redacted>";
- }
- }`);
expect(html).not.toContain("<pre>");
expect(html).toContain("<li>for (const step of rest.steps) {</li>");
expect(html).toContain("<li>if (step.request.body) {</li>");
expect(html).toContain("<li>step.request.body = &quot;&lt;redacted&gt;&quot;;</li>");
});
it("parses inline markdown in recovered list content", () => {
const html = renderMarkdown(
"- **important** [docs](https://example.com) use `inline code`, not ~~plain text~~",
);
expect(html).toContain("<strong>important</strong>");
expect(html).toContain('<a href="https://example.com">docs</a>');
expect(html).toContain("<code>inline code</code>");
expect(html).toContain("<del>plain text</del>");
expect(html).not.toContain("**important**");
});
it("preserves every recovered block separated by blank lines", () => {
const html = renderMarkdown(`- **first block**
[second block](https://example.com)`);
expect(html).toContain("<strong>first block</strong>");
expect(html).toContain('<a href="https://example.com">second block</a>');
});
it("recursively normalizes lists in recovered tail blocks", () => {
const html = renderMarkdown(`- first block
- nested block`);
expect(html).not.toContain("<pre>");
expect(html).toContain("<li>nested block</li>");
});
it("preserves fenced code blocks within list items", () => {
const html = renderMarkdown(`- \`\`\`ts
const value = 1;
\`\`\``);
expect(html).toContain('<pre><code class="language-ts">const value = 1;');
});
it("preserves indented code blocks that start below a list marker", () => {
const html = renderMarkdown(`-
const value = 1;`);
expect(html).toContain("<pre><code>const value = 1;");
});
it("preserves same-line code blocks without excess indentation", () => {
const html = renderMarkdown("- const value = 1;");
expect(html).toContain("<pre><code>const value = 1;");
});
});
+143
View File
@@ -0,0 +1,143 @@
interface MarkdownPosition {
readonly start?: {
readonly line?: number;
readonly offset?: number;
};
}
interface MarkdownAstNode {
readonly type: string;
readonly value?: unknown;
readonly position?: MarkdownPosition;
children?: MarkdownAstNode[];
}
interface MarkdownFile {
readonly value?: unknown;
}
interface MarkdownParser {
parse(markdown: string): unknown;
}
interface RecoveredMarkdown {
readonly blocks: MarkdownAstNode[];
readonly source: string;
}
const INLINE_PARSE_PREFIX = "t3-markdown-inline-prefix:";
function isSameLineOverIndentedCode(
node: MarkdownAstNode,
parent: MarkdownAstNode | undefined,
markdown: string,
): boolean {
if (
node.type !== "code" ||
parent?.type !== "listItem" ||
typeof node.value !== "string" ||
!/^[\t ]/.test(node.value)
) {
return false;
}
const nodeStart = node.position?.start;
const parentStart = parent.position?.start;
if (
nodeStart?.line === undefined ||
nodeStart.offset === undefined ||
parentStart?.line === undefined ||
nodeStart.line !== parentStart.line
) {
return false;
}
const sourceCharacter = markdown[nodeStart.offset];
return sourceCharacter !== "`" && sourceCharacter !== "~";
}
function parseRecoveredMarkdown(value: string, parser: MarkdownParser): RecoveredMarkdown {
// A text prefix forces block-looking input into a paragraph while preserving
// the processor's configured inline extensions (for example, GFM syntax).
// Later root children are kept as blocks so blank-line-separated content is
// never discarded.
const source = `${INLINE_PARSE_PREFIX}${value}`;
const document = parser.parse(source) as MarkdownAstNode;
const blocks = document.children;
const paragraph = blocks?.[0];
const children = paragraph?.type === "paragraph" ? paragraph.children : undefined;
const first = children?.[0];
if (
!blocks ||
!children ||
first?.type !== "text" ||
typeof first.value !== "string" ||
!first.value.startsWith(INLINE_PARSE_PREFIX)
) {
return { blocks: [{ type: "text", value }], source };
}
const firstValue = first.value.slice(INLINE_PARSE_PREFIX.length);
return {
blocks: [
{
...paragraph,
type: "paragraph",
children: [...(firstValue ? [{ ...first, value: firstValue }] : []), ...children.slice(1)],
},
...blocks.slice(1),
],
source,
};
}
function blocksFromIndentedCode(node: MarkdownAstNode, parser: MarkdownParser): RecoveredMarkdown {
const value = typeof node.value === "string" ? node.value.trim() : "";
const recovered = parseRecoveredMarkdown(value, parser);
const first = recovered.blocks[0];
return {
...recovered,
blocks:
first && node.position
? [{ ...first, position: node.position }, ...recovered.blocks.slice(1)]
: recovered.blocks,
};
}
/**
* CommonMark treats four or more spaces after a list marker as an indented
* code block. In chat output, excessive spacing is commonly accidental
* alignment such as `- text`, which otherwise produces a full code card
* for every bullet. Only normalize blocks that retain excess indentation and
* start on the marker's own line; explicit fences and conventional indented
* blocks remain code.
*/
function attachListItemIndentationNormalizer(this: MarkdownParser) {
return (tree: MarkdownAstNode, file: MarkdownFile) => {
if (typeof file.value !== "string") {
return;
}
const markdown = file.value;
const visit = (node: MarkdownAstNode, source: string) => {
if (!node.children) {
return;
}
node.children = node.children.flatMap((child) => {
if (isSameLineOverIndentedCode(child, node, source)) {
const recovered = blocksFromIndentedCode(child, this);
for (const block of recovered.blocks) {
visit(block, recovered.source);
}
return recovered.blocks;
}
visit(child, source);
return [child];
});
};
visit(tree, markdown);
};
}
export const remarkNormalizeListItemIndentation = attachListItemIndentationNormalizer;
+71 -10
View File
@@ -31,16 +31,77 @@ export interface SidebarProjectSnapshot extends Project {
remoteEnvironmentLabels: readonly string[];
}
interface SidebarProjectGroupCandidate {
readonly logicalKey: string;
readonly project: Project;
}
function getProjectFreshnessTime(project: Project): number {
const updatedAtTime = Date.parse(project.updatedAt);
if (Number.isFinite(updatedAtTime)) {
return updatedAtTime;
}
const createdAtTime = Date.parse(project.createdAt);
return Number.isFinite(createdAtTime) ? createdAtTime : 0;
}
function shouldReplaceDuplicateMember(input: {
existingMember: Project;
candidateMember: Project;
primaryEnvironmentId: EnvironmentId | null;
}): boolean {
if (
input.primaryEnvironmentId !== null &&
input.existingMember.environmentId !== input.primaryEnvironmentId &&
input.candidateMember.environmentId === input.primaryEnvironmentId
) {
return true;
}
const existingFreshness = getProjectFreshnessTime(input.existingMember);
const candidateFreshness = getProjectFreshnessTime(input.candidateMember);
if (candidateFreshness !== existingFreshness) {
return candidateFreshness > existingFreshness;
}
return input.candidateMember.id > input.existingMember.id;
}
function collectProjectWinnersByPhysicalKey(input: {
projects: ReadonlyArray<Project>;
settings: ProjectGroupingSettings;
primaryEnvironmentId: EnvironmentId | null;
}): Map<string, SidebarProjectGroupCandidate> {
const winnersByPhysicalKey = new Map<string, SidebarProjectGroupCandidate>();
for (const project of input.projects) {
const logicalKey = deriveLogicalProjectKeyFromSettings(project, input.settings);
const physicalProjectKey = derivePhysicalProjectKey(project);
const existing = winnersByPhysicalKey.get(physicalProjectKey);
if (!existing) {
winnersByPhysicalKey.set(physicalProjectKey, { logicalKey, project });
continue;
}
if (
shouldReplaceDuplicateMember({
existingMember: existing.project,
candidateMember: project,
primaryEnvironmentId: input.primaryEnvironmentId,
})
) {
winnersByPhysicalKey.set(physicalProjectKey, { logicalKey, project });
}
}
return winnersByPhysicalKey;
}
export function buildPhysicalToLogicalProjectKeyMap(input: {
projects: ReadonlyArray<Project>;
settings: ProjectGroupingSettings;
primaryEnvironmentId: EnvironmentId | null;
}): Map<string, string> {
const mapping = new Map<string, string>();
for (const project of input.projects) {
mapping.set(
derivePhysicalProjectKey(project),
deriveLogicalProjectKeyFromSettings(project, input.settings),
);
for (const [physicalProjectKey, winner] of collectProjectWinnersByPhysicalKey(input)) {
mapping.set(physicalProjectKey, winner.logicalKey);
}
return mapping;
}
@@ -56,17 +117,17 @@ export function buildSidebarProjectSnapshots(input: {
// legacy behavior.
isDesktopLocalEnvironment?: (environmentId: EnvironmentId) => boolean;
}): SidebarProjectSnapshot[] {
const winnersByPhysicalKey = collectProjectWinnersByPhysicalKey(input);
const groupedMembers = new Map<string, SidebarProjectGroupMember[]>();
for (const project of input.projects) {
const logicalKey = deriveLogicalProjectKeyFromSettings(project, input.settings);
for (const { logicalKey, project } of winnersByPhysicalKey.values()) {
const member: SidebarProjectGroupMember = {
...project,
physicalProjectKey: derivePhysicalProjectKey(project),
environmentLabel: input.resolveEnvironmentLabel(project.environmentId),
};
const existing = groupedMembers.get(logicalKey);
if (existing) {
existing.push(member);
const existingMembers = groupedMembers.get(logicalKey);
if (existingMembers) {
existingMembers.push(member);
} else {
groupedMembers.set(logicalKey, [member]);
}
+17 -25
View File
@@ -60,11 +60,11 @@ sequenceDiagram
Transport-->>Browser: Hydrate initial state
```
1. The browser boots [`WsTransport`][1] and registers typed listeners in [`wsNativeApi`][2].
2. The server accepts the connection in [`wsServer`][3] and brings up the runtime graph defined in [`serverLayers`][7].
3. [`ServerReadiness`][4] waits until the key startup barriers are complete.
4. Once the server is ready, [`wsServer`][3] sends `server.welcome` from the contracts in [`ws.ts`][6] through [`ServerPushBus`][5].
5. The browser receives that ordered push through [`WsTransport`][1], and [`wsNativeApi`][2] uses it to seed local client state.
1. The browser boots `WsTransport` and registers typed listeners in `wsNativeApi`.
2. The server accepts the connection in `wsServer` and brings up the runtime graph defined in `serverLayers`.
3. `ServerReadiness` waits until the key startup barriers are complete.
4. Once the server is ready, `wsServer` sends `server.welcome` from the contracts in `ws.ts` through `ServerPushBus`.
5. The browser receives that ordered push through `WsTransport`, and `wsNativeApi` uses it to seed local client state.
### User turn flow
@@ -90,12 +90,12 @@ sequenceDiagram
Push-->>Browser: Typed push
```
1. A user action in the browser becomes a typed request through [`WsTransport`][1] and the browser API layer in [`nativeApi`][12].
2. [`wsServer`][3] decodes that request using the shared WebSocket contracts in [`ws.ts`][6] and routes it to the right service.
1. A user action in the browser becomes a typed request through `WsTransport` and the browser API layer in `nativeApi`.
2. `wsServer` decodes that request using the shared WebSocket contracts in `ws.ts` and routes it to the right service.
3. [`ProviderService`][8] starts or resumes a session and talks to `codex app-server` over JSON-RPC on stdio.
4. Provider-native events are pulled back into the server by [`ProviderRuntimeIngestion`][9], which converts them into orchestration events.
5. [`OrchestrationEngine`][10] persists those events, updates the read model, and exposes them as domain events.
6. [`wsServer`][3] pushes those updates to the browser through [`ServerPushBus`][5] on channels defined in [`orchestration.ts`][11].
6. `wsServer` pushes those updates to the browser through `ServerPushBus` on channels defined in [`orchestration.ts`][11].
### Async completion flow
@@ -123,21 +123,13 @@ sequenceDiagram
2. These flows run as queue-backed workers using [`DrainableWorker`][16], which helps keep side effects ordered and test synchronization deterministic.
3. When a milestone completes, the server emits a typed receipt on [`RuntimeReceiptBus`][15], such as checkpoint completion or turn quiescence.
4. Tests and orchestration code wait on those receipts instead of polling git state, projections, or timers.
5. Any user-visible state changes produced by that async work still go back through [`wsServer`][3] and [`ServerPushBus`][5].
5. Any user-visible state changes produced by that async work still go back through `wsServer` and `ServerPushBus`.
[1]: ../apps/web/src/wsTransport.ts
[2]: ../apps/web/src/wsNativeApi.ts
[3]: ../apps/server/src/wsServer.ts
[4]: ../apps/server/src/wsServer/readiness.ts
[5]: ../apps/server/src/wsServer/pushBus.ts
[6]: ../packages/contracts/src/ws.ts
[7]: ../apps/server/src/serverLayers.ts
[8]: ../apps/server/src/provider/Layers/ProviderService.ts
[9]: ../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
[10]: ../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
[11]: ../packages/contracts/src/orchestration.ts
[12]: ../apps/web/src/nativeApi.ts
[13]: ../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
[14]: ../apps/server/src/orchestration/Layers/CheckpointReactor.ts
[15]: ../apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts
[16]: ../packages/shared/src/DrainableWorker.ts
[8]: ../../apps/server/src/provider/Layers/ProviderService.ts
[9]: ../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
[10]: ../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts
[11]: ../../packages/contracts/src/orchestration.ts
[13]: ../../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
[14]: ../../apps/server/src/orchestration/Layers/CheckpointReactor.ts
[15]: ../../apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts
[16]: ../../packages/shared/src/DrainableWorker.ts
+1 -1
View File
@@ -1,6 +1,6 @@
# CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
- `.github/workflows/ci.yml` runs `vp check` (lint + typecheck), `vpr typecheck`, and `vp run test` on pull requests and pushes to `main`.
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when platform credentials are present. macOS passkey builds additionally require `APPLE_TEAM_ID` and the `MACOS_PROVISIONING_PROFILE` secret; Windows uses Azure Trusted Signing. Without the core signing credentials, it still releases unsigned artifacts.
- See [Release Checklist](./release.md) for the full release/signing setup checklist.
+89 -89
View File
@@ -56,43 +56,43 @@ Effect.fn("name")(
### `apps/server/src/provider/Layers/ClaudeAdapter.ts` (`62`)
- [x] [buildUserMessageEffect](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L554)
- [x] [makeClaudeAdapter](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L913)
- [x] [startSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2414)
- [x] [sendTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2887)
- [x] [interruptTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2975)
- [x] [readThread](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2984)
- [x] [rollbackThread](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2990)
- [x] [stopSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L3039)
- [x] [buildUserMessageEffect](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L554)
- [x] [makeClaudeAdapter](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L913)
- [x] [startSession](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L2414)
- [x] [sendTurn](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L2887)
- [x] [interruptTurn](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L2975)
- [x] [readThread](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L2984)
- [x] [rollbackThread](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L2990)
- [x] [stopSession](../../apps/server/src/provider/Layers/ClaudeAdapter.ts#L3039)
- [x] Internal helpers and callback wrappers in this file
### `apps/server/src/git/Layers/GitCore.ts` (`58`)
- [x] [makeGitCore](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L513)
- [x] [handleTraceLine](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L324)
- [x] [emitCompleteLines](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L455)
- [x] [commit](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1190)
- [x] [pushCurrentBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1223)
- [x] [pullCurrentBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1323)
- [x] [checkoutBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1727)
- [x] [makeGitCore](../../apps/server/src/git/Layers/GitCore.ts#L513)
- [x] [handleTraceLine](../../apps/server/src/git/Layers/GitCore.ts#L324)
- [x] [emitCompleteLines](../../apps/server/src/git/Layers/GitCore.ts#L455)
- [x] [commit](../../apps/server/src/git/Layers/GitCore.ts#L1190)
- [x] [pushCurrentBranch](../../apps/server/src/git/Layers/GitCore.ts#L1223)
- [x] [pullCurrentBranch](../../apps/server/src/git/Layers/GitCore.ts#L1323)
- [x] [checkoutBranch](../../apps/server/src/git/Layers/GitCore.ts#L1727)
- [x] Service methods and callback wrappers in this file
### `apps/server/src/git/Layers/GitManager.ts` (`28`)
- [x] [configurePullRequestHeadUpstream](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L387)
- [x] [materializePullRequestHeadBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L428)
- [x] [findOpenPr](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L576)
- [x] [findLatestPr](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L602)
- [x] [runCommitStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L728)
- [x] [runPrStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L842)
- [x] [runFeatureBranchStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L1106)
- [x] [configurePullRequestHeadUpstream](../../apps/server/src/git/Layers/GitManager.ts#L387)
- [x] [materializePullRequestHeadBranch](../../apps/server/src/git/Layers/GitManager.ts#L428)
- [x] [findOpenPr](../../apps/server/src/git/Layers/GitManager.ts#L576)
- [x] [findLatestPr](../../apps/server/src/git/Layers/GitManager.ts#L602)
- [x] [runCommitStep](../../apps/server/src/git/Layers/GitManager.ts#L728)
- [x] [runPrStep](../../apps/server/src/git/Layers/GitManager.ts#L842)
- [x] [runFeatureBranchStep](../../apps/server/src/git/Layers/GitManager.ts#L1106)
- [x] Remaining helpers and nested callback wrappers in this file
### `apps/server/src/orchestration/Layers/ProjectionPipeline.ts` (`25`)
- [x] [runProjectorForEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L1161)
- [x] [applyProjectsProjection](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L357)
- [x] [applyThreadsProjection](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L415)
- [x] [runProjectorForEvent](../../apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L1161)
- [x] [applyProjectsProjection](../../apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L357)
- [x] [applyThreadsProjection](../../apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L415)
- [x] `Effect.forEach(..., threadId => Effect.gen(...))` callbacks around `L250`
- [x] `Effect.forEach(..., entry => Effect.gen(...))` callbacks around `L264`
- [x] `Effect.forEach(..., entry => Effect.gen(...))` callbacks around `L305`
@@ -100,98 +100,98 @@ Effect.fn("name")(
### `apps/server/src/provider/Layers/ProviderService.ts` (`24`)
- [ ] [makeProviderService](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L134)
- [ ] [recoverSessionForThread](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L196)
- [ ] [resolveRoutableSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L255)
- [ ] [startSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L284)
- [ ] [sendTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L347)
- [ ] [interruptTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L393)
- [ ] [respondToRequest](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L411)
- [ ] [respondToUserInput](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L430)
- [ ] [stopSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L445)
- [ ] [listSessions](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L466)
- [ ] [rollbackConversation](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L516)
- [ ] [runStopAll](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L538)
- [ ] [makeProviderService](../../apps/server/src/provider/Layers/ProviderService.ts#L134)
- [ ] [recoverSessionForThread](../../apps/server/src/provider/Layers/ProviderService.ts#L196)
- [ ] [resolveRoutableSession](../../apps/server/src/provider/Layers/ProviderService.ts#L255)
- [ ] [startSession](../../apps/server/src/provider/Layers/ProviderService.ts#L284)
- [ ] [sendTurn](../../apps/server/src/provider/Layers/ProviderService.ts#L347)
- [ ] [interruptTurn](../../apps/server/src/provider/Layers/ProviderService.ts#L393)
- [ ] [respondToRequest](../../apps/server/src/provider/Layers/ProviderService.ts#L411)
- [ ] [respondToUserInput](../../apps/server/src/provider/Layers/ProviderService.ts#L430)
- [ ] [stopSession](../../apps/server/src/provider/Layers/ProviderService.ts#L445)
- [ ] [listSessions](../../apps/server/src/provider/Layers/ProviderService.ts#L466)
- [ ] [rollbackConversation](../../apps/server/src/provider/Layers/ProviderService.ts#L516)
- [ ] [runStopAll](../../apps/server/src/provider/Layers/ProviderService.ts#L538)
### `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` (`14`)
- [x] [finalizeAssistantMessage](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L680)
- [x] [upsertProposedPlan](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L722)
- [x] [finalizeBufferedProposedPlan](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L761)
- [x] [clearTurnStateForSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L800)
- [x] [processRuntimeEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L908)
- [x] [finalizeAssistantMessage](../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L680)
- [x] [upsertProposedPlan](../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L722)
- [x] [finalizeBufferedProposedPlan](../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L761)
- [x] [clearTurnStateForSession](../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L800)
- [x] [processRuntimeEvent](../../apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L908)
- [x] Nested callback wrappers in this file
### `apps/server/src/provider/Layers/CodexAdapter.ts` (`12`)
- [x] [makeCodexAdapter](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1317)
- [x] [sendTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1399)
- [x] [writeNativeEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1546)
- [x] [listener](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1555)
- [x] [makeCodexAdapter](../../apps/server/src/provider/Layers/CodexAdapter.ts#L1317)
- [x] [sendTurn](../../apps/server/src/provider/Layers/CodexAdapter.ts#L1399)
- [x] [writeNativeEvent](../../apps/server/src/provider/Layers/CodexAdapter.ts#L1546)
- [x] [listener](../../apps/server/src/provider/Layers/CodexAdapter.ts#L1555)
- [x] Remaining nested callback wrappers in this file
### `apps/server/src/checkpointing/CheckpointStore.ts` (`10`)
- [ ] [captureCheckpoint](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/CheckpointStore.ts#L123)
- [ ] [restoreCheckpoint](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/CheckpointStore.ts#L137)
- [ ] [diffCheckpoints](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/CheckpointStore.ts#L144)
- [ ] [deleteCheckpointRefs](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/CheckpointStore.ts#L151)
- [ ] [captureCheckpoint](../../apps/server/src/checkpointing/CheckpointStore.ts#L123)
- [ ] [restoreCheckpoint](../../apps/server/src/checkpointing/CheckpointStore.ts#L137)
- [ ] [diffCheckpoints](../../apps/server/src/checkpointing/CheckpointStore.ts#L144)
- [ ] [deleteCheckpointRefs](../../apps/server/src/checkpointing/CheckpointStore.ts#L151)
- [ ] Nested callback wrappers in this file
### `apps/server/src/provider/Layers/EventNdjsonLogger.ts` (`9`)
- [ ] [toLogMessage](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L77)
- [ ] [makeThreadWriter](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L102)
- [ ] [makeEventNdjsonLogger](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L174)
- [ ] [write](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L231)
- [ ] [close](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L247)
- [ ] [toLogMessage](../../apps/server/src/provider/Layers/EventNdjsonLogger.ts#L77)
- [ ] [makeThreadWriter](../../apps/server/src/provider/Layers/EventNdjsonLogger.ts#L102)
- [ ] [makeEventNdjsonLogger](../../apps/server/src/provider/Layers/EventNdjsonLogger.ts#L174)
- [ ] [write](../../apps/server/src/provider/Layers/EventNdjsonLogger.ts#L231)
- [ ] [close](../../apps/server/src/provider/Layers/EventNdjsonLogger.ts#L247)
- [ ] Flush and writer-resolution callback wrappers in this file
### `apps/server/scripts/cli.ts` (`8`)
- [ ] Command handlers around [cli.ts](/Users/julius/Development/Work/codething-mvp/apps/server/scripts/cli.ts#L125)
- [ ] Command handlers around [cli.ts](/Users/julius/Development/Work/codething-mvp/apps/server/scripts/cli.ts#L170)
- [ ] Resource callbacks around [cli.ts](/Users/julius/Development/Work/codething-mvp/apps/server/scripts/cli.ts#L221)
- [ ] Resource callbacks around [cli.ts](/Users/julius/Development/Work/codething-mvp/apps/server/scripts/cli.ts#L239)
- [ ] Command handlers around [cli.ts](../../apps/server/scripts/cli.ts#L125)
- [ ] Command handlers around [cli.ts](../../apps/server/scripts/cli.ts#L170)
- [ ] Resource callbacks around [cli.ts](../../apps/server/scripts/cli.ts#L221)
- [ ] Resource callbacks around [cli.ts](../../apps/server/scripts/cli.ts#L239)
### `apps/server/src/orchestration/Layers/OrchestrationEngine.ts` (`7`)
- [ ] [processEnvelope](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L64)
- [ ] [dispatch](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L218)
- [ ] Catch/stream callback wrappers around [OrchestrationEngine.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L162)
- [ ] Catch/stream callback wrappers around [OrchestrationEngine.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L200)
- [ ] [processEnvelope](../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L64)
- [ ] [dispatch](../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L218)
- [ ] Catch/stream callback wrappers around [OrchestrationEngine.ts](../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L162)
- [ ] Catch/stream callback wrappers around [OrchestrationEngine.ts](../../apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L200)
### `apps/server/src/orchestration/projector.ts` (`5`)
- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L242)
- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L336)
- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L397)
- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L446)
- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L478)
- [ ] `switch` branch wrapper at [projector.ts](../../apps/server/src/orchestration/projector.ts#L242)
- [ ] `switch` branch wrapper at [projector.ts](../../apps/server/src/orchestration/projector.ts#L336)
- [ ] `switch` branch wrapper at [projector.ts](../../apps/server/src/orchestration/projector.ts#L397)
- [ ] `switch` branch wrapper at [projector.ts](../../apps/server/src/orchestration/projector.ts#L446)
- [ ] `switch` branch wrapper at [projector.ts](../../apps/server/src/orchestration/projector.ts#L478)
### Smaller clusters
- [ ] [packages/shared/src/DrainableWorker.ts](/Users/julius/Development/Work/codething-mvp/packages/shared/src/DrainableWorker.ts) (`4`)
- [ ] [apps/server/src/wsServer/pushBus.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/wsServer/pushBus.ts) (`4`)
- [ ] [apps/server/src/wsServer.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/wsServer.ts) (`4`)
- [ ] [apps/server/src/provider/Layers/ProviderRegistry.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderRegistry.ts) (`4`)
- [ ] [apps/server/src/persistence/Layers/Sqlite.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/persistence/Layers/Sqlite.ts) (`4`)
- [ ] [apps/server/src/orchestration/Layers/ProviderCommandReactor.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts) (`4`)
- [ ] [apps/server/src/main.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/main.ts) (`4`)
- [ ] [apps/server/src/keybindings.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/keybindings.ts) (`4`)
- [ ] [apps/server/src/git/Layers/CodexTextGeneration.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/CodexTextGeneration.ts) (`4`)
- [ ] [apps/server/src/serverLayers.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/serverLayers.ts) (`3`)
- [ ] [apps/server/src/telemetry/Layers/AnalyticsService.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/telemetry/Layers/AnalyticsService.ts) (`2`)
- [ ] [apps/server/src/telemetry/Identify.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/telemetry/Identify.ts) (`2`)
- [ ] [apps/server/src/provider/Layers/ProviderAdapterRegistry.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts) (`2`)
- [ ] [apps/server/src/provider/Layers/CodexProvider.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexProvider.ts) (`2`)
- [ ] [apps/server/src/provider/Layers/ClaudeProvider.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeProvider.ts) (`2`)
- [ ] [apps/server/src/persistence/NodeSqliteClient.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/persistence/NodeSqliteClient.ts) (`2`)
- [ ] [apps/server/src/persistence/Migrations.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/persistence/Migrations.ts) (`2`)
- [ ] [apps/server/src/open.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/open.ts) (`2`)
- [ ] [apps/server/src/git/Layers/ClaudeTextGeneration.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/ClaudeTextGeneration.ts) (`2`)
- [ ] [apps/server/src/checkpointing/CheckpointDiffQuery.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/CheckpointDiffQuery.ts) (`2`)
- [ ] [apps/server/src/provider/makeManagedServerProvider.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/makeManagedServerProvider.ts) (`1`)
- [ ] [packages/shared/src/DrainableWorker.ts](../../packages/shared/src/DrainableWorker.ts) (`4`)
- [ ] [apps/server/src/wsServer/pushBus.ts](../../apps/server/src/wsServer/pushBus.ts) (`4`)
- [ ] [apps/server/src/wsServer.ts](../../apps/server/src/wsServer.ts) (`4`)
- [ ] [apps/server/src/provider/Layers/ProviderRegistry.ts](../../apps/server/src/provider/Layers/ProviderRegistry.ts) (`4`)
- [ ] [apps/server/src/persistence/Layers/Sqlite.ts](../../apps/server/src/persistence/Layers/Sqlite.ts) (`4`)
- [ ] [apps/server/src/orchestration/Layers/ProviderCommandReactor.ts](../../apps/server/src/orchestration/Layers/ProviderCommandReactor.ts) (`4`)
- [ ] [apps/server/src/main.ts](../../apps/server/src/main.ts) (`4`)
- [ ] [apps/server/src/keybindings.ts](../../apps/server/src/keybindings.ts) (`4`)
- [ ] [apps/server/src/git/Layers/CodexTextGeneration.ts](../../apps/server/src/git/Layers/CodexTextGeneration.ts) (`4`)
- [ ] [apps/server/src/serverLayers.ts](../../apps/server/src/serverLayers.ts) (`3`)
- [ ] [apps/server/src/telemetry/Layers/AnalyticsService.ts](../../apps/server/src/telemetry/Layers/AnalyticsService.ts) (`2`)
- [ ] [apps/server/src/telemetry/Identify.ts](../../apps/server/src/telemetry/Identify.ts) (`2`)
- [ ] [apps/server/src/provider/Layers/ProviderAdapterRegistry.ts](../../apps/server/src/provider/Layers/ProviderAdapterRegistry.ts) (`2`)
- [ ] [apps/server/src/provider/Layers/CodexProvider.ts](../../apps/server/src/provider/Layers/CodexProvider.ts) (`2`)
- [ ] [apps/server/src/provider/Layers/ClaudeProvider.ts](../../apps/server/src/provider/Layers/ClaudeProvider.ts) (`2`)
- [ ] [apps/server/src/persistence/NodeSqliteClient.ts](../../apps/server/src/persistence/NodeSqliteClient.ts) (`2`)
- [ ] [apps/server/src/persistence/Migrations.ts](../../apps/server/src/persistence/Migrations.ts) (`2`)
- [ ] [apps/server/src/open.ts](../../apps/server/src/open.ts) (`2`)
- [ ] [apps/server/src/git/Layers/ClaudeTextGeneration.ts](../../apps/server/src/git/Layers/ClaudeTextGeneration.ts) (`2`)
- [ ] [apps/server/src/checkpointing/CheckpointDiffQuery.ts](../../apps/server/src/checkpointing/CheckpointDiffQuery.ts) (`2`)
- [ ] [apps/server/src/provider/makeManagedServerProvider.ts](../../apps/server/src/provider/makeManagedServerProvider.ts) (`1`)
```
@@ -64,6 +64,7 @@ function makeAgentActivityRows(
remove: () => Effect.void,
pruneTerminal: () => Effect.void,
listForUser: () => Effect.succeed([state]),
getForUserThread: () => Effect.succeed(state),
...overrides,
};
}
@@ -75,6 +75,15 @@ describe("AgentActivityRows", () => {
const listError = yield* rows.listForUser({ userId: "user-2" }).pipe(Effect.flip);
expect(listError).toMatchObject({ userId: "user-2", cause });
expect(listError.message).toBe("Failed to list agent activity state for user user-2.");
const getError = yield* rows
.getForUserThread({
userId: "user-2",
environmentId: "env-1",
threadId: "thread-1",
})
.pipe(Effect.flip);
expect(getError).toMatchObject({ userId: "user-2", cause });
}).pipe(
Effect.provide(
AgentActivityRows.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, failingDb))),
@@ -83,6 +83,11 @@ export class AgentActivityRows extends Context.Service<
ReadonlyArray<RelayAgentActivityState>,
AgentActivityRowListPersistenceError
>;
readonly getForUserThread: (input: {
readonly userId: string;
readonly environmentId: string;
readonly threadId: string;
}) => Effect.Effect<RelayAgentActivityState | null, AgentActivityRowListPersistenceError>;
}
>()("t3code-relay/agentActivity/AgentActivityRows") {}
@@ -241,6 +246,54 @@ export const make = Effect.gen(function* () {
),
);
}),
getForUserThread: Effect.fn("relay.agent_activity_rows.get_for_user_thread")(function* (input) {
return yield* db
.select({ stateJson: relayAgentActivityRows.stateJson })
.from(relayAgentActivityRows)
.innerJoin(
relayEnvironmentLinks,
and(
eq(relayEnvironmentLinks.environmentId, relayAgentActivityRows.environmentId),
eq(
relayEnvironmentLinks.environmentPublicKey,
relayAgentActivityRows.environmentPublicKey,
),
),
)
.where(
and(
eq(relayEnvironmentLinks.userId, input.userId),
isNull(relayEnvironmentLinks.revokedAt),
eq(relayAgentActivityRows.environmentId, input.environmentId),
eq(relayAgentActivityRows.threadId, input.threadId),
),
)
.orderBy(desc(relayAgentActivityRows.updatedAt))
.pipe(
Effect.flatMap((rows) =>
Effect.forEach(rows, (row) => encodeJsonValue(row.stateJson), {
concurrency: "unbounded",
}),
),
Effect.map((rows) => {
for (const row of rows) {
const decoded = decodeRelayAgentActivityStateJson(row);
if (Option.isSome(decoded)) {
return decoded.value;
}
}
return null;
}),
Effect.mapError(
(cause) =>
new AgentActivityRowListPersistenceError({
userId: input.userId,
cause,
}),
),
);
}),
});
});
@@ -5,7 +5,6 @@ import type {
import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
import { describe, expect, it } from "@effect/vitest";
import * as NodeCrypto from "node:crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
@@ -161,10 +160,13 @@ function makeLayer(input: {
>;
readonly currentTargets?: ReadonlyArray<LiveActivities.TargetRow>;
readonly config?: RelayConfiguration.RelayConfiguration["Service"];
// Live agent-activity rows returned by the delivery-time start recheck.
// Defaults to one freshly-updated running thread so queued starts stay
// deliverable in tests that don't care about the recheck.
// Live agent-activity rows returned by delivery-time state rechecks.
// Defaults to the fixture row so queued updates match unless a test is
// explicitly exercising stale-state behavior.
readonly activityStates?: ReadonlyArray<RelayAgentActivityState>;
// Current per-thread rows used to reject queued updates/notifications that
// have been superseded before APNs delivery.
readonly currentActivityStates?: ReadonlyArray<RelayAgentActivityState>;
readonly execute?: (
request: HttpClientRequest.HttpClientRequest,
) => Effect.Effect<HttpClientResponse.HttpClientResponse>;
@@ -182,9 +184,14 @@ function makeLayer(input: {
listForUser: () =>
input.activityStates !== undefined
? Effect.succeed([...input.activityStates])
: DateTime.now.pipe(
Effect.map((now) => [{ ...state, updatedAt: DateTime.formatIso(now) }]),
),
: Effect.succeed([state]),
getForUserThread: ({ environmentId, threadId }) =>
Effect.succeed(
(input.currentActivityStates ?? input.activityStates ?? [state]).find(
(current) =>
current.environmentId === environmentId && current.threadId === threadId,
) ?? null,
),
} satisfies AgentActivityRows.AgentActivityRows["Service"]),
Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, {
send: (body) =>
@@ -674,6 +681,8 @@ describe("ApnsDeliveries", () => {
environmentId: "env",
threadId: "thread",
deepLink: "/",
phase: "waiting_for_input",
updatedAt: state.updatedAt,
},
},
},
@@ -778,6 +787,30 @@ describe("ApnsDeliveries", () => {
},
);
it.effect("does not queue a push notification when a thread starts working", () => {
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
const queuedJobs: Array<SignedApnsDeliveryJob> = [];
return Effect.gen(function* () {
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
const result = yield* deliveries.sendForTarget({
target: {
...target,
push_token: "apns-device-token",
push_to_start_token: null,
activity_push_token: null,
remote_started_at: null,
},
aggregate,
nowMs: 5_000,
});
expect(result).toBeNull();
expect(queuedJobs).toEqual([]);
expect(attempts).toEqual([]);
}).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));
});
it.effect("queues bounded alert notification payloads", () => {
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
const queuedJobs: Array<SignedApnsDeliveryJob> = [];
@@ -1176,6 +1209,150 @@ describe("ApnsDeliveries", () => {
);
});
it.effect("skips a queued Done Live Activity update after the thread resumes working", () => {
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
let executeCount = 0;
const completedAt = "1970-01-01T00:00:01.000Z";
const completedAggregate: RelayAgentActivityAggregateState = {
...aggregate,
activeCount: 0,
updatedAt: completedAt,
activities: [
{
...aggregate.activities[0]!,
phase: "completed",
status: "Done",
updatedAt: completedAt,
},
],
};
const payload = makeApnsDeliveryJobPayload({
kind: "live_activity_update",
userId: target.user_id,
deviceId: target.device_id,
token: target.activity_push_token ?? "activity-token",
aggregate: completedAggregate,
alert: { title: "Thread", body: "Done: Project" },
createdAt: completedAt,
expiresAt: "1970-01-01T00:10:00.000Z",
jobId: "job-update-superseded-by-running",
});
const signed = signApnsDeliveryJob({
secret: config.apnsDeliveryJobSigningSecret,
payload,
});
const execute = (request: HttpClientRequest.HttpClientRequest) =>
Effect.sync(() => {
executeCount += 1;
return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
});
return Effect.gen(function* () {
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
const result = yield* deliveries.processSignedJob(signed);
expect(result).toMatchObject({
kind: "live_activity_update",
ok: true,
apnsStatus: null,
apnsReason: "Stale APNs delivery job skipped.",
});
expect(executeCount).toBe(0);
expect(attempts).toMatchObject([
{
sourceJobId: "job-update-superseded-by-running",
apnsReason: "Stale agent activity state skipped.",
},
]);
}).pipe(
Effect.provide(
makeLayer({
attempts,
activityStates: [
{
...state,
phase: "running",
headline: "Running",
updatedAt: "1970-01-01T00:00:02.000Z",
},
],
config: signingConfig,
execute,
}),
),
);
});
it.effect("skips a queued Done notification after the thread resumes working", () => {
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
let executeCount = 0;
const completedAt = "1970-01-01T00:00:01.000Z";
const payload = makeApnsDeliveryJobPayload({
kind: "push_notification",
userId: target.user_id,
deviceId: target.device_id,
token: "apns-device-token",
aggregate: null,
notification: {
title: "Thread",
body: "Done: Project",
environmentId: "env",
threadId: "thread",
deepLink: "/",
phase: "completed",
updatedAt: completedAt,
},
createdAt: completedAt,
expiresAt: "1970-01-01T00:10:00.000Z",
jobId: "job-push-superseded-by-running",
});
const signed = signApnsDeliveryJob({
secret: config.apnsDeliveryJobSigningSecret,
payload,
});
const execute = (request: HttpClientRequest.HttpClientRequest) =>
Effect.sync(() => {
executeCount += 1;
return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
});
return Effect.gen(function* () {
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
const result = yield* deliveries.processSignedJob(signed);
expect(result).toMatchObject({
kind: "push_notification",
ok: true,
apnsStatus: null,
apnsReason: "Stale APNs delivery job skipped.",
});
expect(executeCount).toBe(0);
expect(attempts).toMatchObject([
{
sourceJobId: "job-push-superseded-by-running",
apnsReason: "Stale agent activity state skipped.",
},
]);
}).pipe(
Effect.provide(
makeLayer({
attempts,
currentTargets: [{ ...target, push_token: "apns-device-token" }],
currentActivityStates: [
{
...state,
phase: "running",
headline: "Running",
updatedAt: "1970-01-01T00:00:02.000Z",
},
],
config: signingConfig,
execute,
}),
),
);
});
it.effect("retries signed queue jobs that are already claimed but not completed", () => {
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
let executeCount = 0;
@@ -1327,7 +1504,15 @@ describe("ApnsDeliveries", () => {
deviceId: target.device_id,
},
]);
}).pipe(Effect.provide(makeLayer({ attempts, clearedStarts })));
}).pipe(
Effect.provide(
makeLayer({
attempts,
clearedStarts,
activityStates: [{ ...state, updatedAt: "9999-01-01T00:00:00.000Z" }],
}),
),
);
});
it.effect("invalidates dead push-to-start tokens after permanent APNs start failures", () => {
@@ -1373,7 +1558,15 @@ describe("ApnsDeliveries", () => {
},
]);
}).pipe(
Effect.provide(makeLayer({ attempts, invalidatedTokens, config: signingConfig, execute })),
Effect.provide(
makeLayer({
attempts,
invalidatedTokens,
activityStates: [{ ...state, updatedAt: "9999-01-01T00:00:00.000Z" }],
config: signingConfig,
execute,
}),
),
);
});
@@ -369,6 +369,8 @@ function notificationForAggregate(input: {
environmentId: activity.environmentId,
threadId: activity.threadId,
deepLink: activity.deepLink,
phase: activity.phase,
updatedAt: activity.updatedAt,
};
}
@@ -722,6 +724,87 @@ export const make = Effect.gen(function* () {
);
});
const stateIdentityIsCurrent = Effect.fnUntraced(function* (input: {
readonly userId: string;
readonly environmentId: string;
readonly threadId: string;
readonly phase: RelayAgentActivityAggregateState["activities"][number]["phase"];
readonly updatedAt: string;
}) {
return yield* activityRows
.getForUserThread({
userId: input.userId,
environmentId: input.environmentId,
threadId: input.threadId,
})
.pipe(
Effect.map(
(current) =>
current !== null &&
current.phase === input.phase &&
current.updatedAt === input.updatedAt,
),
// A transient persistence failure must not permanently discard a
// legitimate alert. Fail open and let the signed job's retry/dedupe
// protections handle transport failures as usual.
Effect.catchCause((cause) =>
Effect.logWarning("agent-activity state recheck failed; allowing queued delivery", {
cause,
environmentId: input.environmentId,
threadId: input.threadId,
}).pipe(Effect.as(true)),
),
);
});
const aggregateRowsAreCurrent = Effect.fnUntraced(function* (input: {
readonly userId: string;
readonly aggregate: RelayAgentActivityAggregateState;
}) {
return yield* activityRows.listForUser({ userId: input.userId }).pipe(
Effect.map((currentStates) => {
const currentByThread = new Map(
currentStates.map((current) => [
`${current.environmentId}\u0000${current.threadId}`,
current,
]),
);
return input.aggregate.activities.every((row) => {
const current = currentByThread.get(`${row.environmentId}\u0000${row.threadId}`);
return (
current !== undefined &&
current.phase === row.phase &&
current.updatedAt === row.updatedAt
);
});
}),
Effect.catchCause((cause) =>
Effect.logWarning("agent-activity aggregate recheck failed; allowing queued delivery", {
cause,
userId: input.userId,
}).pipe(Effect.as(true)),
),
);
});
const notificationStateIsCurrent = Effect.fnUntraced(function* (input: {
readonly userId: string;
readonly notification: ApnsNotificationPayload;
}) {
// Jobs from older relay versions do not carry a state identity. Preserve
// backwards compatibility and only revalidate newly queued jobs.
if (input.notification.phase === undefined || input.notification.updatedAt === undefined) {
return true;
}
return yield* stateIdentityIsCurrent({
userId: input.userId,
environmentId: input.notification.environmentId,
threadId: input.notification.threadId,
phase: input.notification.phase,
updatedAt: input.notification.updatedAt,
});
});
const isCurrentSignedJobToken = Effect.fnUntraced(function* (input: {
readonly target: LiveActivityDeliveryTarget;
readonly kind: RelayDeliveryKind;
@@ -791,6 +874,20 @@ export const make = Effect.gen(function* () {
});
return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });
}
if (
input.kind !== "live_activity_start" &&
aggregate !== null &&
!(yield* aggregateRowsAreCurrent({
userId: input.target.user_id,
aggregate,
}))
) {
yield* attempts.completeSourceJob({
sourceJobId: input.sourceJobId,
apnsReason: "Stale agent activity state skipped.",
});
return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });
}
}
if (
input.kind === "live_activity_start" &&
@@ -930,6 +1027,21 @@ export const make = Effect.gen(function* () {
kind: "push_notification",
});
}
if (
!(yield* notificationStateIsCurrent({
userId: input.target.user_id,
notification,
}))
) {
yield* attempts.completeSourceJob({
sourceJobId: input.sourceJobId,
apnsReason: "Stale agent activity state skipped.",
});
return staleJobResult({
deviceId: input.target.device_id,
kind: "push_notification",
});
}
}
const result = yield* apns
.sendPushNotificationRequest({
@@ -86,6 +86,7 @@ function makeAgentActivityRows(
};
return Effect.succeed([activeState]);
},
getForUserThread: () => Effect.succeed(null),
...overrides,
};
}
@@ -1,6 +1,10 @@
import * as NodeCrypto from "node:crypto";
import { RelayAgentActivityAggregateState, type RelayDeliveryKind } from "@t3tools/contracts/relay";
import {
RelayAgentActivityAggregateState,
RelayAgentAwarenessPhase,
type RelayDeliveryKind,
} from "@t3tools/contracts/relay";
import { stableStringify } from "@t3tools/shared/relaySigning";
import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
@@ -38,6 +42,11 @@ export const ApnsNotificationPayload = Schema.Struct({
environmentId: Schema.String,
threadId: Schema.String,
deepLink: Schema.String,
// Optional so delivery jobs queued by older relay builds still decode.
// New jobs use these fields to avoid delivering a stale Done/attention
// notification after the thread has moved to another phase.
phase: Schema.optional(RelayAgentAwarenessPhase),
updatedAt: Schema.optional(Schema.String),
});
export type ApnsNotificationPayload = typeof ApnsNotificationPayload.Type;
+4
View File
@@ -35,6 +35,10 @@
"types": "./src/platform/index.ts",
"default": "./src/platform/index.ts"
},
"./preview": {
"types": "./src/preview/index.ts",
"default": "./src/preview/index.ts"
},
"./relay": {
"types": "./src/relay/index.ts",
"default": "./src/relay/index.ts"
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more