Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 55038ce366 Fix trace diagnostics validation issues
Co-authored-by: Julius Marminge <[email protected]>
2026-07-08 16:18:20 +00:00
Cursor AgentandJulius Marminge 5429dfb4d5 Fix GitHub PR list Effect decoder
Co-authored-by: Julius Marminge <[email protected]>
2026-07-08 16:16:22 +00:00
Cursor AgentandJulius Marminge baaba34c7b Refine Effect JSON decoding patterns
Co-authored-by: Julius Marminge <[email protected]>
2026-07-08 16:15:20 +00:00
Rowan 0c66565854 fix(release): bump electron-builder so pnpm 11 deduped deps land in the asar (#3790) 2026-07-08 04:38:45 -07:00
Julius Marminge e775bc6228 Upgrade Clerk toolchain to latest versions (#3785) 2026-07-08 04:30:07 -07:00
15 changed files with 400 additions and 1198 deletions

No files matched your search

+1 -1
View File
@@ -31,7 +31,7 @@
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"electron-builder": "26.8.1",
"electron-builder": "26.15.6",
"tailwindcss": "^4.0.0",
"vite-plus": "catalog:"
},
-26
View File
@@ -181,32 +181,6 @@ const config: ExpoConfig = {
description: "Shows the current state of active T3 Code agents.",
supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],
},
{
name: "NewThread",
displayName: "New Thread",
description: "Start a new T3 Code thread right from your Home Screen.",
supportedFamilies: ["systemSmall", "systemMedium", "systemLarge"],
// Per-instance options in the long-press "Edit Widget" sheet. Enum
// parameters are compiled into Swift at prebuild, so the dynamic
// project list cannot be offered as a picker — pins are typed as
// text and matched against the synced projects inside the widget.
configuration: {
title: "New Thread",
description: "Pin specific projects; the rest fills with your latest activity.",
parameters: {
pinnedProjects: {
title: "Pinned projects (comma-separated)",
type: "string",
default: "",
},
showRecent: {
title: "Fill with recent projects",
type: "boolean",
default: true,
},
},
},
},
],
},
],
-3
View File
@@ -40,7 +40,6 @@ import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute
import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen";
import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";
import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";
import { useNewThreadWidgetSync } from "./features/threads/use-new-thread-widget-sync";
import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
@@ -257,8 +256,6 @@ function RootStackLayout(props: {
useThreadOutboxDrain();
// Presents the T3 Connect onboarding sheet after an in-session sign-in.
useConnectOnboardingNavigation();
// Keeps the NewThread home-screen widget's project shortcuts current.
useNewThreadWidgetSync();
// Full pathname (sheets included) for keyboard-command scoping; the
// workspace layout only reacts to the underlying non-overlay route.
const path = getPathFromState(props.state, navigationPathConfig);
@@ -1,155 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { makeNewThreadWidgetProps } from "./new-thread-widget";
function makeProject(overrides: {
readonly id: string;
readonly environmentId?: string;
readonly title?: string;
readonly updatedAt?: string;
}): EnvironmentProject {
return {
id: overrides.id,
environmentId: overrides.environmentId ?? "env-1",
title: overrides.title ?? overrides.id,
updatedAt: overrides.updatedAt ?? "2026-07-01T00:00:00.000Z",
} as unknown as EnvironmentProject;
}
function makeThread(overrides: {
readonly projectId: string;
readonly environmentId?: string;
readonly updatedAt: string;
}): EnvironmentThreadShell {
return {
id: `thread-${overrides.projectId}`,
projectId: overrides.projectId,
environmentId: overrides.environmentId ?? "env-1",
updatedAt: overrides.updatedAt,
} as unknown as EnvironmentThreadShell;
}
describe("makeNewThreadWidgetProps", () => {
it("orders projects by their newest thread activity", () => {
const props = makeNewThreadWidgetProps(
[
makeProject({ id: "stale", updatedAt: "2026-07-06T00:00:00.000Z" }),
makeProject({ id: "busy", updatedAt: "2026-07-01T00:00:00.000Z" }),
],
[makeThread({ projectId: "busy", updatedAt: "2026-07-07T00:00:00.000Z" })],
);
expect(props.projects?.map((project) => project.title)).toEqual(["busy", "stale"]);
});
it("falls back to the project's own updatedAt when it has no threads", () => {
const props = makeNewThreadWidgetProps(
[
makeProject({ id: "old", updatedAt: "2026-07-01T00:00:00.000Z" }),
makeProject({ id: "fresh", updatedAt: "2026-07-07T00:00:00.000Z" }),
],
[],
);
expect(props.projects?.map((project) => project.title)).toEqual(["fresh", "old"]);
});
it("ignores thread activity from a same-named project in another environment", () => {
const props = makeNewThreadWidgetProps(
[
makeProject({ id: "proj", environmentId: "env-1", title: "one" }),
makeProject({
id: "proj",
environmentId: "env-2",
title: "two",
updatedAt: "2026-07-02T00:00:00.000Z",
}),
],
[
makeThread({
projectId: "proj",
environmentId: "env-2",
updatedAt: "2026-07-07T00:00:00.000Z",
}),
],
);
expect(props.projects?.map((project) => project.title)).toEqual(["two", "one"]);
});
it("syncs every project so low-activity pins can still resolve", () => {
const count = 25;
const props = makeNewThreadWidgetProps(
Array.from({ length: count }, (_, n) =>
makeProject({
id: `p${n}`,
updatedAt: `2026-06-${String(n + 1).padStart(2, "0")}T00:00:00.000Z`,
}),
),
[],
);
expect(props.projects).toHaveLength(count);
expect(props.projects?.[0]?.title).toBe(`p${count - 1}`);
expect(props.projects?.[count - 1]?.title).toBe("p0");
});
it("disambiguates duplicate titles with environment labels", () => {
const props = makeNewThreadWidgetProps(
[
makeProject({
id: "proj-a",
environmentId: "env-1",
title: "t3code",
updatedAt: "2026-07-07T00:00:00.000Z",
}),
makeProject({
id: "proj-b",
environmentId: "env-2",
title: "t3code",
updatedAt: "2026-07-01T00:00:00.000Z",
}),
],
[],
new Map([
["env-1", "Laptop"],
["env-2", "Desktop"],
]),
);
expect(props.projects?.map((project) => project.title)).toEqual([
"t3code (Laptop)",
"t3code (Desktop)",
]);
expect(props.projects?.[0]?.deepLink).toContain("environmentId=env-1");
expect(props.projects?.[0]?.deepLink).toContain("title=t3code");
expect(props.projects?.[1]?.deepLink).toContain("environmentId=env-2");
});
it("falls back to environment id when labels are missing for duplicates", () => {
const props = makeNewThreadWidgetProps(
[
makeProject({ id: "a", environmentId: "env-1", title: "shared" }),
makeProject({ id: "b", environmentId: "env-2", title: "shared" }),
],
[],
);
expect(props.projects?.map((project) => project.title)).toEqual([
"shared (env-1)",
"shared (env-2)",
]);
});
it("URL-encodes deep link parameters", () => {
const props = makeNewThreadWidgetProps(
[makeProject({ id: "p 1", environmentId: "env&1", title: "T3 & friends" })],
[],
);
expect(props.projects?.[0]?.deepLink).toBe(
"/new/draft?environmentId=env%261&projectId=p%201&title=T3%20%26%20friends",
);
});
it("returns an empty list when there are no projects", () => {
expect(makeNewThreadWidgetProps([], []).projects).toEqual([]);
});
});
@@ -1,100 +0,0 @@
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { NewThreadWidgetProps } from "../../widgets/NewThread";
/**
* Builds the home-screen widget payload: all projects ordered by recent
* activity, each with a deep link into the new-task draft composer.
*
* The full set is synced (not just the visible rows) so pinned-project matching
* inside the widget can resolve a deliberately pinned low-activity project.
* Medium shows 3 rows and large 7; the widget layout slices after pin matching.
*
* "Recently active" means the newest thread update in the project, falling
* back to the project's own updatedAt for projects with no threads — so the
* widget surfaces where the user actually works, not what was created last.
*
* When two projects share a title, the display title is disambiguated with the
* environment label (falling back to environment id, then project id) so pin
* matching and the deep link target the intended workspace.
*/
export function makeNewThreadWidgetProps(
projects: ReadonlyArray<EnvironmentProject>,
threads: ReadonlyArray<EnvironmentThreadShell>,
environmentLabels: ReadonlyMap<string, string> = new Map(),
): NewThreadWidgetProps {
const latestThreadActivity = new Map<string, string>();
for (const thread of threads) {
const key = projectActivityKey(thread.environmentId, thread.projectId);
const previous = latestThreadActivity.get(key);
// ISO-8601 timestamps order lexicographically.
if (previous === undefined || thread.updatedAt > previous) {
latestThreadActivity.set(key, thread.updatedAt);
}
}
const lastActivity = (project: EnvironmentProject): string => {
const threadActivity = latestThreadActivity.get(
projectActivityKey(project.environmentId, project.id),
);
return threadActivity !== undefined && threadActivity > project.updatedAt
? threadActivity
: project.updatedAt;
};
const ordered = [...projects].sort((a, b) => lastActivity(b).localeCompare(lastActivity(a)));
const displayTitles = disambiguateProjectTitles(ordered, environmentLabels);
return {
projects: ordered.map((project, index) => ({
title: displayTitles[index] ?? project.title,
// Matches the NewTaskSheet > NewTaskDraft linking config in Stack.tsx;
// the widget layout prefixes the scheme after a safety check. Keep the
// original project title in the query — not the disambiguated display.
deepLink:
`/new/draft?environmentId=${encodeURIComponent(String(project.environmentId))}` +
`&projectId=${encodeURIComponent(String(project.id))}` +
`&title=${encodeURIComponent(project.title)}`,
})),
};
}
function disambiguateProjectTitles(
projects: ReadonlyArray<EnvironmentProject>,
environmentLabels: ReadonlyMap<string, string>,
): string[] {
const titleCounts = countBy((project) => project.title.toLowerCase(), projects);
const withEnvironment = projects.map((project) => {
if ((titleCounts.get(project.title.toLowerCase()) ?? 0) <= 1) {
return project.title;
}
const envLabel =
environmentLabels.get(String(project.environmentId)) ?? String(project.environmentId);
return `${project.title} (${envLabel})`;
});
const envTitleCounts = countBy((title) => title.toLowerCase(), withEnvironment);
return withEnvironment.map((title, index) => {
if ((envTitleCounts.get(title.toLowerCase()) ?? 0) <= 1) {
return title;
}
const project = projects[index];
return project ? `${title} · ${project.id}` : title;
});
}
function countBy<T>(keyOf: (value: T) => string, values: ReadonlyArray<T>): Map<string, number> {
const counts = new Map<string, number>();
for (const value of values) {
const key = keyOf(value);
counts.set(key, (counts.get(key) ?? 0) + 1);
}
return counts;
}
function projectActivityKey(environmentId: string, projectId: string): string {
return `${environmentId}\u0000${projectId}`;
}
@@ -1,75 +0,0 @@
import { useEffect, useMemo } from "react";
import { Platform } from "react-native";
import { useProjects, useThreadShells } from "../../state/entities";
import { useEnvironments } from "../../state/environments";
import NewThreadWidget from "../../widgets/NewThread";
import { makeNewThreadWidgetProps } from "./new-thread-widget";
// Last payload written to the widget timeline. Module-level (not React state)
// so navigator remounts don't rewrite an unchanged payload: every write ends
// in a WidgetCenter reload, and iOS throttles widgets that reload too often.
let lastSyncedSignature: string | null = null;
/** Delay before retrying a failed snapshot write while entity data is unchanged. */
const SNAPSHOT_RETRY_MS = 5_000;
/**
* Keeps the NewThread home-screen widget's project shortcuts in sync with the
* workspace. Writing the snapshot also persists the widget layout to the
* shared app group, which is what lets the widget render at all — so this
* must run on every launch, not only when projects change.
*/
export function useNewThreadWidgetSync(): void {
const projects = useProjects();
const threads = useThreadShells();
const { environments } = useEnvironments();
const environmentLabels = useMemo(() => {
const labels = new Map<string, string>();
for (const environment of environments) {
labels.set(String(environment.environmentId), environment.label);
}
return labels;
}, [environments]);
useEffect(() => {
if (Platform.OS !== "ios") {
return;
}
let cancelled = false;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
const sync = () => {
if (cancelled) {
return;
}
const props = makeNewThreadWidgetProps(projects, threads, environmentLabels);
const signature = JSON.stringify(props);
if (signature === lastSyncedSignature) {
return;
}
try {
NewThreadWidget.updateSnapshot(props);
lastSyncedSignature = signature;
} catch (error) {
// Do not treat the write as succeeded. Schedule a retry so a transient
// app-group failure still recovers when projects/threads stay the same.
lastSyncedSignature = null;
if (__DEV__) {
console.warn("[new-thread-widget] snapshot update failed", error);
}
retryTimer = setTimeout(sync, SNAPSHOT_RETRY_MS);
}
};
sync();
return () => {
cancelled = true;
if (retryTimer !== null) {
clearTimeout(retryTimer);
}
};
}, [projects, threads, environmentLabels]);
}
-283
View File
@@ -1,283 +0,0 @@
import { describe, expect, it, vi } from "vite-plus/test";
vi.mock("@expo/ui/swift-ui", () => ({
HStack: "HStack",
Image: "Image",
Link: "Link",
Spacer: "Spacer",
Text: "Text",
VStack: "VStack",
}));
vi.mock("@expo/ui/swift-ui/modifiers", () => ({
containerBackground: (color: unknown) => ({ containerBackground: color }),
font: (value: unknown) => value,
foregroundStyle: (value: unknown) => value,
frame: (value: unknown) => value,
lineLimit: (value: unknown) => value,
padding: (value: unknown) => value,
resizable: (value: unknown) => value,
widgetURL: (value: unknown) => ({ widgetURL: value }),
}));
vi.mock("expo-widgets", () => ({
createWidget: vi.fn((name: string, layout: unknown) => ({ layout, name })),
}));
import {
NewThread,
type NewThreadWidgetConfiguration,
type NewThreadWidgetProject,
} from "./NewThread";
function makeProject(overrides: Partial<NewThreadWidgetProject>): NewThreadWidgetProject {
return {
title: "Project",
deepLink: "/new/draft?environmentId=env-1&projectId=proj-1&title=Project",
...overrides,
};
}
function makeEnvironment(overrides: {
readonly widgetFamily: "systemSmall" | "systemMedium" | "systemLarge";
readonly colorScheme?: "light" | "dark";
readonly configuration?: Partial<NewThreadWidgetConfiguration>;
}) {
return {
date: new Date("2026-07-07T12:00:00.000Z"),
widgetFamily: overrides.widgetFamily,
colorScheme: overrides.colorScheme ?? "dark",
configuration: { pinnedProjects: "", showRecent: true, ...overrides.configuration },
} as never;
}
const smallEnvironment = makeEnvironment({ widgetFamily: "systemSmall" });
const mediumEnvironment = makeEnvironment({ widgetFamily: "systemMedium" });
describe("NewThread widget layout", () => {
it("deep links the whole small widget to the new-task sheet", () => {
const layout = JSON.stringify(NewThread({ projects: [] }, smallEnvironment));
expect(layout).toContain('"widgetURL":"t3code://new"');
expect(layout).toContain("New Thread");
});
it("renders the small call to action even when projects are present", () => {
const layout = JSON.stringify(
NewThread({ projects: [makeProject({ title: "t3code" })] }, smallEnvironment),
);
expect(layout).not.toContain("t3code://new/draft");
expect(layout).toContain('"widgetURL":"t3code://new"');
});
it("tolerates missing props and configuration (WidgetKit placeholder renders with none)", () => {
const layout = JSON.stringify(
NewThread(
{} as never,
{
date: new Date("2026-07-07T12:00:00.000Z"),
widgetFamily: "systemMedium",
colorScheme: "light",
configuration: undefined,
} as never,
),
);
expect(layout).toContain('"widgetURL":"t3code://new"');
});
it("links each medium row to its project's draft composer", () => {
const layout = JSON.stringify(
NewThread(
{
projects: [
makeProject({ title: "t3code", deepLink: "/new/draft?projectId=a" }),
makeProject({ title: "marketing", deepLink: "/new/draft?projectId=b" }),
],
},
mediumEnvironment,
),
);
expect(layout).toContain("t3code");
expect(layout).toContain("marketing");
expect(layout).toContain('"destination":"t3code://new/draft?projectId=a"');
expect(layout).toContain('"destination":"t3code://new/draft?projectId=b"');
// Header link falls back to the plain new-task sheet.
expect(layout).toContain('"destination":"t3code://new"');
});
it("renders at most three rows on medium and seven on large", () => {
const projects = [1, 2, 3, 4, 5, 6, 7, 8].map((n) =>
makeProject({ title: `Project ${n}`, deepLink: `/new/draft?projectId=p${n}` }),
);
const medium = JSON.stringify(NewThread({ projects }, mediumEnvironment));
expect(medium).toContain("Project 3");
expect(medium).not.toContain("Project 4");
const large = JSON.stringify(
NewThread({ projects }, makeEnvironment({ widgetFamily: "systemLarge" })),
);
expect(large).toContain("Project 7");
expect(large).not.toContain("Project 8");
});
it("pins configured projects ahead of recents, in pin order", () => {
const layout = JSON.stringify(
NewThread(
{
projects: [
makeProject({ title: "recent" }),
makeProject({ title: "beta" }),
makeProject({ title: "alpha" }),
],
},
makeEnvironment({
widgetFamily: "systemMedium",
configuration: { pinnedProjects: "Alpha, Beta" },
}),
),
);
expect(layout.indexOf("alpha")).toBeLessThan(layout.indexOf("beta"));
expect(layout.indexOf("beta")).toBeLessThan(layout.indexOf("recent"));
// Pinned rows carry the pin glyph; the recent row keeps the folder.
expect(layout).toContain("pin.fill");
expect(layout).toContain("folder");
});
it("matches pins by case-insensitive prefix and skips unmatched pins", () => {
const layout = JSON.stringify(
NewThread(
{
projects: [makeProject({ title: "recent" }), makeProject({ title: "T3 Marketing Site" })],
},
makeEnvironment({
widgetFamily: "systemMedium",
configuration: { pinnedProjects: "t3 mark, no-such-project" },
}),
),
);
expect(layout.indexOf("T3 Marketing Site")).toBeLessThan(layout.indexOf("recent"));
expect(layout).toContain("pin.fill");
});
it("pins can surface projects beyond the visible row budget", () => {
const projects = [1, 2, 3, 4, 5].map((n) => makeProject({ title: `Project ${n}` }));
const layout = JSON.stringify(
NewThread(
{ projects },
makeEnvironment({
widgetFamily: "systemMedium",
configuration: { pinnedProjects: "Project 5" },
}),
),
);
expect(layout).toContain("Project 5");
expect(layout).toContain("Project 1");
expect(layout).toContain("Project 2");
expect(layout).not.toContain("Project 3");
});
it("skips ambiguous pin titles instead of linking the first match", () => {
const layout = JSON.stringify(
NewThread(
{
projects: [
makeProject({
title: "t3code (Laptop)",
deepLink: "/new/draft?environmentId=env-1&projectId=a&title=t3code",
}),
makeProject({
title: "t3code (Desktop)",
deepLink: "/new/draft?environmentId=env-2&projectId=b&title=t3code",
}),
makeProject({ title: "recent", deepLink: "/new/draft?projectId=recent" }),
],
},
makeEnvironment({
widgetFamily: "systemMedium",
configuration: { pinnedProjects: "t3code", showRecent: false },
}),
),
);
// Ambiguous bare title must not deep-link either duplicate.
expect(layout).not.toContain("environmentId=env-1");
expect(layout).not.toContain("environmentId=env-2");
expect(layout).toContain('"widgetURL":"t3code://new"');
});
it("pins a disambiguated title to the intended environment", () => {
const layout = JSON.stringify(
NewThread(
{
projects: [
makeProject({
title: "t3code (Laptop)",
deepLink: "/new/draft?environmentId=env-1&projectId=a&title=t3code",
}),
makeProject({
title: "t3code (Desktop)",
deepLink: "/new/draft?environmentId=env-2&projectId=b&title=t3code",
}),
],
},
makeEnvironment({
widgetFamily: "systemMedium",
configuration: { pinnedProjects: "t3code (Desktop)", showRecent: false },
}),
),
);
expect(layout).toContain("t3code (Desktop)");
expect(layout).toContain(
'"destination":"t3code://new/draft?environmentId=env-2&projectId=b&title=t3code"',
);
expect(layout).not.toContain("environmentId=env-1");
});
it("hides recents when the fill toggle is off", () => {
const layout = JSON.stringify(
NewThread(
{ projects: [makeProject({ title: "pinned-one" }), makeProject({ title: "recent" })] },
makeEnvironment({
widgetFamily: "systemMedium",
configuration: { pinnedProjects: "pinned-one", showRecent: false },
}),
),
);
expect(layout).toContain("pinned-one");
expect(layout).not.toContain("recent");
});
it("falls back to the call to action when recents are off and no pin matches", () => {
const layout = JSON.stringify(
NewThread(
{ projects: [makeProject({ title: "recent" })] },
makeEnvironment({
widgetFamily: "systemMedium",
configuration: { pinnedProjects: "gone", showRecent: false },
}),
),
);
expect(layout).toContain('"widgetURL":"t3code://new"');
expect(layout).not.toContain("recent");
});
it("drops the link but keeps the row for unsafe deep links", () => {
const layout = JSON.stringify(
NewThread(
{ projects: [makeProject({ title: "sneaky", deepLink: "//evil.example" })] },
mediumEnvironment,
),
);
expect(layout).toContain("sneaky");
expect(layout).not.toContain("evil.example");
});
it("adapts the container background to the color scheme", () => {
const dark = JSON.stringify(NewThread({ projects: [] }, smallEnvironment));
const light = JSON.stringify(
NewThread(
{ projects: [] },
makeEnvironment({ widgetFamily: "systemSmall", colorScheme: "light" }),
),
);
expect(dark).toContain('"containerBackground":"#0a0a0a"');
expect(light).toContain('"containerBackground":"#ffffff"');
});
});
-211
View File
@@ -1,211 +0,0 @@
import { HStack, Image, Link, Spacer, Text, VStack } from "@expo/ui/swift-ui";
import type { ComponentProps, JSX } from "react";
import {
containerBackground,
font,
foregroundStyle,
frame,
lineLimit,
padding,
resizable,
widgetURL,
} from "@expo/ui/swift-ui/modifiers";
import { createWidget, type WidgetEnvironment } from "expo-widgets";
export interface NewThreadWidgetProject {
readonly title: string;
/** App-relative path to the prefilled draft composer, e.g. "/new/draft?environmentId=…". */
readonly deepLink: string;
}
export interface NewThreadWidgetProps {
/**
* Candidate projects, most recently active first. The medium/large widgets
* render a slice of these as one-tap shortcuts into the draft composer.
* The full workspace set is synced (not just the visible rows): pinned-
* project matching happens here in the widget (the configuration is per
* widget instance, so the app cannot precompute it), and a pin should
* resolve even when its project has fallen out of the top displayed rows.
* Optional because WidgetKit renders placeholder/gallery entries with no
* props before the app has ever written a timeline.
*/
readonly projects?: ReadonlyArray<NewThreadWidgetProject>;
}
/** Mirrors the `configuration.parameters` in app.config.ts. */
export interface NewThreadWidgetConfiguration {
/** Comma-separated project titles to pin ahead of recent projects. */
readonly pinnedProjects: string;
/** Whether to fill the remaining rows with recently active projects. */
readonly showRecent: boolean;
}
// This function is serialized into the widget extension's JS bundle, so it
// must stay self-contained: no references to module-scope helpers, only the
// imported view/modifier factories.
export function NewThread(
props: NewThreadWidgetProps,
environment: WidgetEnvironment<NewThreadWidgetConfiguration>,
): JSX.Element {
"widget";
// Semantic label colors adapt to whatever material the OS renders the
// widget on (light/dark home screen, tinted iOS 18 mode).
const primaryForeground = "primary";
const secondaryForeground = "secondary";
// Home-screen widgets must supply their own container background on iOS 17+;
// match the app's splash background per scheme.
const containerColor = environment.colorScheme === "dark" ? "#0a0a0a" : "#ffffff";
// Any registered scheme variant routes back to this app; taps are delivered
// to the widget's containing app, so the prod scheme is safe for all builds.
const newThreadUrl = "t3code://new";
const toWidgetUrl = (deepLink: string): string | null =>
deepLink.startsWith("/") && !deepLink.startsWith("//") ? `t3code://${deepLink.slice(1)}` : null;
// SF Symbols and the logo ignore frame/foregroundStyle applied directly to
// the image; size + tint them through a container the resizable image fills.
type SFName = NonNullable<ComponentProps<typeof Image>["systemName"]>;
const renderGlyph = (systemName: SFName, size: number, color: string) => (
<HStack modifiers={[frame({ width: size, height: size }), foregroundStyle(color)]}>
<Image systemName={systemName} modifiers={[resizable()]} />
</HStack>
);
// The 3:2 frame matches the T3 mark's aspect ratio so it never distorts.
const renderLogo = (height: number, color: string) => (
<HStack modifiers={[frame({ width: height * 1.5, height }), foregroundStyle(color)]}>
<Image assetName="T3Mark" modifiers={[resizable()]} />
</HStack>
);
const available = props.projects ?? [];
const configuration = environment.configuration;
// Pins are typed titles (see app.config.ts for why there is no picker).
// Match case-insensitively, exact title first and then prefix, preserving
// the user's pin order. A query that matches more than one remaining project
// is skipped (no ambiguous deep link) rather than picking the first by
// activity order. Unmatched pins (typo, deleted project) are skipped.
const pinnedQueries = (
typeof configuration?.pinnedProjects === "string" ? configuration.pinnedProjects : ""
)
.split(",")
.map((title) => title.trim().toLowerCase())
.filter((title) => title.length > 0);
const pinned: NewThreadWidgetProject[] = [];
for (const query of pinnedQueries) {
const unused = available.filter((project) => !pinned.includes(project));
const exactMatches = unused.filter((project) => project.title.toLowerCase() === query);
let match: NewThreadWidgetProject | undefined;
if (exactMatches.length === 1) {
match = exactMatches[0];
} else if (exactMatches.length === 0) {
const prefixMatches = unused.filter((project) =>
project.title.toLowerCase().startsWith(query),
);
if (prefixMatches.length === 1) {
match = prefixMatches[0];
}
}
if (match) {
pinned.push(match);
}
}
// Pinned first, then latest activity — unless recents are configured off.
const rows = [...pinned];
if (configuration?.showRecent !== false) {
for (const project of available) {
if (!rows.includes(project)) {
rows.push(project);
}
}
}
const rowLimit = environment.widgetFamily === "systemLarge" ? 7 : 3;
const visible = rows.slice(0, rowLimit);
// The whole small widget is one tap target; the medium/large widgets add
// per-row links, with the root widgetURL as the fallback for untargeted areas.
const rootModifiers = [containerBackground(containerColor, "widget"), widgetURL(newThreadUrl)];
// Small family — and the larger families with nothing to list (no sync yet,
// or recents off with no pin matched) — render a single centered call to action.
if (environment.widgetFamily === "systemSmall" || visible.length === 0) {
return (
<VStack spacing={7} modifiers={rootModifiers}>
<Spacer minLength={0} />
{renderLogo(20, primaryForeground)}
<HStack spacing={5} alignment="center">
{renderGlyph("square.and.pencil", 12, secondaryForeground)}
<Text
modifiers={[font({ weight: "semibold", size: 13 }), foregroundStyle(primaryForeground)]}
>
New Thread
</Text>
</HStack>
<Spacer minLength={0} />
</VStack>
);
}
// Project shortcut row: tapping opens the draft composer with that project
// preselected. Rows whose deep link fails the safety check still render,
// but fall through to the root's plain new-thread tap target.
const renderProjectRow = (project: NewThreadWidgetProject, isPinned: boolean) => {
const url = toWidgetUrl(project.deepLink);
const row = (
<HStack spacing={7} alignment="center">
{renderGlyph(isPinned ? "pin.fill" : "folder", 11, secondaryForeground)}
<Text
modifiers={[
font({ weight: "semibold", size: 13 }),
foregroundStyle(primaryForeground),
lineLimit(1),
]}
>
{project.title}
</Text>
<Spacer minLength={8} />
{renderGlyph("chevron.forward", 9, secondaryForeground)}
</HStack>
);
return url ? <Link destination={url}>{row}</Link> : row;
};
// Pinned rows always precede recents, so index < pinned.length marks them.
const renderRow = (index: number) => {
const project = visible[index];
return project ? renderProjectRow(project, index < pinned.length) : null;
};
return (
<VStack alignment="leading" spacing={8} modifiers={rootModifiers}>
<Link destination={newThreadUrl}>
<HStack spacing={7} alignment="center">
{renderLogo(15, primaryForeground)}
<Text
modifiers={[font({ weight: "bold", size: 14 }), foregroundStyle(primaryForeground)]}
>
New Thread
</Text>
<Spacer minLength={8} />
{renderGlyph("square.and.pencil", 14, secondaryForeground)}
</HStack>
</Link>
<Spacer minLength={0} modifiers={[padding({ vertical: 1 })]} />
{renderRow(0)}
{renderRow(1)}
{renderRow(2)}
{renderRow(3)}
{renderRow(4)}
{renderRow(5)}
{renderRow(6)}
<Spacer minLength={0} />
</VStack>
);
}
export default createWidget<NewThreadWidgetProps, NewThreadWidgetConfiguration>(
"NewThread",
NewThread,
);
@@ -59,6 +59,7 @@ describe("TraceDiagnostics", () => {
durationMs: 50,
}),
"not-json",
'{"name":"missing span fields","durationMs":"not-a-number"}',
].join("\n"),
},
{
@@ -123,7 +124,7 @@ describe("TraceDiagnostics", () => {
}),
"1970-01-01T00:00:05.025Z",
);
assert.equal(diagnostics.parseErrorCount, 1);
assert.equal(diagnostics.parseErrorCount, 2);
assert.equal(diagnostics.failureCount, 2);
assert.equal(diagnostics.interruptionCount, 1);
assert.equal(diagnostics.slowSpanCount, 1);
+59 -55
View File
@@ -16,17 +16,19 @@ import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
interface TraceRecordLike {
readonly name?: unknown;
readonly traceId?: unknown;
readonly spanId?: unknown;
readonly startTimeUnixNano?: unknown;
readonly endTimeUnixNano?: unknown;
readonly durationMs?: unknown;
readonly exit?: unknown;
readonly events?: unknown;
}
const TraceRecordLineSchema = Schema.Struct({
name: Schema.String,
traceId: Schema.String,
spanId: Schema.String,
startTimeUnixNano: Schema.optional(Schema.NullOr(Schema.String)),
endTimeUnixNano: Schema.String,
durationMs: Schema.Finite,
exit: Schema.optional(Schema.Unknown),
events: Schema.optional(Schema.Unknown),
});
const decodeTraceRecordLine = decodeJsonResult(TraceRecordLineSchema);
interface TraceEventLike {
readonly name?: unknown;
@@ -90,37 +92,36 @@ function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyA
return [...backups, traceFilePath];
}
function isRecordObject(value: unknown): value is TraceRecordLike {
function isRecordObject(value: unknown): value is Readonly<Record<string, unknown>> {
return typeof value === "object" && value !== null;
}
function toStringValue(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value : null;
function toStringValue(value: unknown): Option.Option<string> {
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
}
function toNumberValue(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function unixNanoToDateTime(value: unknown): DateTime.Utc | null {
const text = toStringValue(value);
if (!text) return null;
function unixNanoToDateTime(value: unknown): Option.Option<DateTime.Utc> {
const text = Option.getOrUndefined(toStringValue(value));
if (text === undefined) return Option.none();
try {
const millis = Number(BigInt(text) / 1_000_000n);
return Option.getOrNull(DateTime.make(millis));
return DateTime.make(millis);
} catch {
return null;
return Option.none();
}
}
function readExitTag(exit: unknown): string | null {
if (!isRecordObject(exit) || !("_tag" in exit)) return null;
function readExitTag(exit: unknown): Option.Option<string> {
if (!isRecordObject(exit) || !("_tag" in exit)) return Option.none();
return toStringValue(exit._tag);
}
function readExitCause(exit: unknown): string {
if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
return toStringValue(exit.cause)?.trim() ?? "Failure";
return Option.getOrElse(
Option.map(toStringValue(exit.cause), (cause) => cause.trim()),
() => "Failure",
);
}
function isTraceEvent(value: unknown): value is TraceEventLike {
@@ -211,8 +212,8 @@ export function aggregateTraceDiagnostics(
let failureCount = 0;
let interruptionCount = 0;
let slowSpanCount = 0;
let firstSpanAt: DateTime.Utc | null = null;
let lastSpanAt: DateTime.Utc | null = null;
let firstSpanAt = Option.none<DateTime.Utc>();
let lastSpanAt = Option.none<DateTime.Utc>();
const spansByName = new Map<
string,
@@ -229,40 +230,40 @@ export function aggregateTraceDiagnostics(
for (const line of lines) {
if (line.trim().length === 0) continue;
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
const decoded = decodeTraceRecordLine(line);
if (Result.isFailure(decoded)) {
parseErrorCount += 1;
continue;
}
if (!isRecordObject(parsed)) {
parseErrorCount += 1;
continue;
}
const name = toStringValue(parsed.name);
const traceId = toStringValue(parsed.traceId);
const spanId = toStringValue(parsed.spanId);
const durationMs = toNumberValue(parsed.durationMs);
const endedAt = unixNanoToDateTime(parsed.endTimeUnixNano);
const parsed = decoded.success;
const requiredFields = Option.all({
name: toStringValue(parsed.name),
traceId: toStringValue(parsed.traceId),
spanId: toStringValue(parsed.spanId),
durationMs: Option.some(parsed.durationMs),
endedAt: unixNanoToDateTime(parsed.endTimeUnixNano),
});
const startedAt = unixNanoToDateTime(parsed.startTimeUnixNano);
if (!name || !traceId || !spanId || durationMs === null || !endedAt) {
if (Option.isNone(requiredFields)) {
parseErrorCount += 1;
continue;
}
const { durationMs, endedAt, name, spanId, traceId } = requiredFields.value;
recordCount += 1;
firstSpanAt =
startedAt && (firstSpanAt === null || DateTime.isLessThan(startedAt, firstSpanAt))
? startedAt
: firstSpanAt;
lastSpanAt =
lastSpanAt === null || DateTime.isGreaterThan(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
if (
Option.isSome(startedAt) &&
(Option.isNone(firstSpanAt) || DateTime.isLessThan(startedAt.value, firstSpanAt.value))
) {
firstSpanAt = startedAt;
}
if (Option.isNone(lastSpanAt) || DateTime.isGreaterThan(endedAt, lastSpanAt.value)) {
lastSpanAt = Option.some(endedAt);
}
const exitTag = readExitTag(parsed.exit);
const exitTag = Option.getOrUndefined(readExitTag(parsed.exit));
const isFailure = exitTag === "Failure";
const isInterrupted = exitTag === "Interrupted";
if (isFailure) failureCount += 1;
@@ -307,8 +308,8 @@ export function aggregateTraceDiagnostics(
for (const rawEvent of parsed.events) {
if (!isTraceEvent(rawEvent)) continue;
const attributes = readEventAttributes(rawEvent);
const level = toStringValue(attributes["effect.logLevel"]);
if (!level) continue;
const level = Option.getOrUndefined(toStringValue(attributes["effect.logLevel"]));
if (level === undefined) continue;
logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
const normalizedLevel = level.toLowerCase();
@@ -321,8 +322,11 @@ export function aggregateTraceDiagnostics(
continue;
}
const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;
const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
const seenAt = Option.getOrElse(unixNanoToDateTime(rawEvent.timeUnixNano), () => endedAt);
const message = Option.getOrElse(
Option.map(toStringValue(rawEvent.name), (name) => name.trim()),
() => "Log event",
);
latestWarningAndErrorLogs.push({
spanName: name,
level,
@@ -354,8 +358,8 @@ export function aggregateTraceDiagnostics(
readAt,
recordCount,
parseErrorCount,
firstSpanAt: Option.fromNullishOr(firstSpanAt),
lastSpanAt: Option.fromNullishOr(lastSpanAt),
firstSpanAt,
lastSpanAt,
failureCount,
interruptionCount,
slowSpanThresholdMs,
@@ -208,6 +208,28 @@ describe("GitHubCli.layer", () => {
}).pipe(Effect.provide(layer)),
);
it.effect("surfaces tagged decode errors for invalid pull request output", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("not-json")));
const gh = yield* GitHubCli.GitHubCli;
const error = yield* gh
.getPullRequest({
cwd: "/repo",
reference: "#42",
})
.pipe(Effect.flip);
assert.strictEqual(error._tag, "GitHubPullRequestDecodeError");
assert.strictEqual(error.command, "gh");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(
error.message,
"GitHub CLI failed in getPullRequest: GitHub CLI returned invalid pull request JSON.",
);
}).pipe(Effect.provide(layer)),
);
it.effect("reads repository clone URLs", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
+24 -35
View File
@@ -2,7 +2,6 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import {
@@ -13,8 +12,8 @@ import {
import * as VcsProcess from "../vcs/VcsProcess.ts";
import {
decodeGitHubPullRequestJson,
decodeGitHubPullRequestListJson,
decodeGitHubPullRequestJsonEffect,
decodeGitHubPullRequestListJsonEffect,
} from "./gitHubPullRequests.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
@@ -339,22 +338,18 @@ export const make = Effect.gen(function* () {
Effect.flatMap((raw) =>
raw.length === 0
? Effect.succeed([])
: Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubPullRequestListDecodeError({
command: "gh",
cwd: input.cwd,
cause: decoded.failure,
}),
);
}
return Effect.succeed(
decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
);
}),
: decodeGitHubPullRequestListJsonEffect(raw).pipe(
Effect.map((decoded) =>
decoded.map(({ updatedAt: _updatedAt, ...summary }) => summary),
),
Effect.mapError(
(cause) =>
new GitHubPullRequestListDecodeError({
command: "gh",
cwd: input.cwd,
cause,
}),
),
),
),
),
@@ -371,22 +366,16 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubPullRequestDecodeError({
command: "gh",
cwd: input.cwd,
cause: decoded.failure,
}),
);
}
return Effect.succeed(
(({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
);
}),
decodeGitHubPullRequestJsonEffect(raw).pipe(
Effect.map(({ updatedAt: _updatedAt, ...summary }) => summary),
Effect.mapError(
(cause) =>
new GitHubPullRequestDecodeError({
command: "gh",
cwd: input.cwd,
cause,
}),
),
),
),
),
@@ -1,5 +1,6 @@
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
@@ -97,6 +98,13 @@ function normalizeGitHubPullRequestRecord(
const decodeGitHubPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
const decodeGitHubPullRequest = decodeJsonResult(GitHubPullRequestSchema);
const decodeGitHubPullRequestEntry = Schema.decodeUnknownExit(GitHubPullRequestSchema);
const decodeGitHubPullRequestListEffect = Schema.decodeEffect(
Schema.fromJsonString(Schema.Array(Schema.Unknown)),
);
const decodeGitHubPullRequestEffect = Schema.decodeEffect(
Schema.fromJsonString(GitHubPullRequestSchema),
);
const decodeGitHubPullRequestEntryEffect = Schema.decodeUnknownEffect(GitHubPullRequestSchema);
export const formatGitHubJsonDecodeError = formatSchemaError;
@@ -130,3 +138,24 @@ export function decodeGitHubPullRequestJson(
}
return Result.fail(result.failure);
}
export function decodeGitHubPullRequestListJsonEffect(
raw: string,
): Effect.Effect<ReadonlyArray<NormalizedGitHubPullRequestRecord>, Schema.SchemaError> {
return Effect.gen(function* () {
const entries = yield* decodeGitHubPullRequestListEffect(raw);
const decoded = yield* Effect.forEach(entries, (entry) =>
decodeGitHubPullRequestEntryEffect(entry).pipe(
Effect.map(normalizeGitHubPullRequestRecord),
Effect.option,
),
);
return decoded.flatMap((entry) => (Option.isSome(entry) ? [entry.value] : []));
});
}
export function decodeGitHubPullRequestJsonEffect(
raw: string,
): Effect.Effect<NormalizedGitHubPullRequestRecord, Schema.SchemaError> {
return decodeGitHubPullRequestEffect(raw).pipe(Effect.map(normalizeGitHubPullRequestRecord));
}
+249 -247
View File
File diff suppressed because it is too large. Load diff
+14 -6
View File
@@ -23,13 +23,13 @@ allowBuilds:
workerd: false
catalog:
"@clerk/backend": 3.8.4
"@clerk/clerk-js": 6.22.0
"@clerk/electron": 0.0.5
"@clerk/backend": 3.11.1
"@clerk/clerk-js": 6.25.0
"@clerk/electron": 0.0.10
"@clerk/electron-passkeys": 0.0.3
"@clerk/expo": 3.6.2
"@clerk/react": 6.11.1
"@clerk/shared": 4.22.0
"@clerk/expo": 3.7.1
"@clerk/react": 6.12.0
"@clerk/shared": 4.25.0
"@effect/atom-react": 4.0.0-beta.78
"@effect/openapi-generator": 4.0.0-beta.78
"@effect/platform-bun": 4.0.0-beta.78
@@ -51,6 +51,14 @@ catalog:
vite-plus: 0.2.2
yaml: ^2.9.0
minimumReleaseAgeExclude:
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
overrides:
"@clerk/backend": "catalog:"
"@clerk/clerk-js": "catalog:"