Skip to content
161 changes: 161 additions & 0 deletions apps/mobile/src/features/threads/thread-workflow-opening.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import { RegistryProvider } from "@effect/atom-react";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import {
EnvironmentId,
MessageId,
NodeId,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import { Atom } from "effect/reactivity";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { expect, it, vi } from "vite-plus/test";

import { v2Projection } from "../../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures";

vi.mock("react-native", () => ({ Pressable: "button", View: "div" }));
vi.mock("@react-navigation/native", () => ({ StackActions: {}, useNavigation: vi.fn() }));
vi.mock("../../components/ui/AppText", () => ({ AppText: "span" }));
vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({
useAppearancePreferences: vi.fn(),
}));
vi.mock("./markdownCodeHighlightState", () => ({ useMarkdownCodeHighlight: vi.fn() }));
vi.mock("./useOpenLinkedThread", () => ({ useOpenLinkedThread: vi.fn() }));
vi.mock("./SubagentRow", () => ({ SubagentRow: "div" }));
vi.mock("./work-log-layout", () => ({ WorkLogBlock: "div" }));
vi.mock("../../state/threads", () => ({ environmentThreadDetails: { threadAtom: vi.fn() } }));

import { environmentThreadDetails } from "../../state/threads";
import { useWorkflowOpening } from "./thread-workflow-opening";

const environmentId = EnvironmentId.make("test-environment");
const threadId = ThreadId.make("new-thread");

function setup() {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
const container = document.createElement("div");
const root = createRoot(container);
const loads: string[] = [];
const available = new Map<string, typeof v2Projection>();
const detailAtom = Atom.family((id: string) =>
Atom.make(() => {
loads.push(id);
return available.has(id) ? { environmentId, projection: available.get(id)! } : null;
}),
);
vi.mocked(environmentThreadDetails.threadAtom).mockImplementation((ref) =>
detailAtom(ref.threadId),
);
function Consumer({ ready }: { ready: boolean }) {
const opening = useWorkflowOpening(ready ? scopeThreadRef(environmentId, threadId) : null);
return (
<span>{opening === null ? "ordinary thread" : `${opening.name}: ${opening.script}`}</span>
);
}
return {
container,
loads,
available,
render: async (ready: boolean) => {
await act(async () =>
root.render(
<RegistryProvider>
<Consumer ready={ready} />
</RegistryProvider>,
),
);
},
async [Symbol.asyncDispose]() {
await act(async () => root.unmount());
vi.mocked(environmentThreadDetails.threadAtom).mockReset();
vi.unstubAllGlobals();
},
};
}

it("does not load a pending thread before creation, then loads it after delivery without a restart", async () => {
await using test = setup();
await test.render(false);
expect(test.loads).toEqual([]);
test.available.set(threadId, v2Projection);
await test.render(true);
expect(test.loads).toEqual([threadId]);
});

it("loads an existing ordinary thread without loading a parent", async () => {
await using test = setup();
test.available.set(threadId, v2Projection);
await test.render(true);
expect(test.loads).toEqual([threadId]);
expect(environmentThreadDetails.threadAtom).toHaveBeenCalledWith(
scopeThreadRef(environmentId, threadId),
);
});

it("loads an existing workflow and its parent metadata", async () => {
await using test = setup();
const parentId = ThreadId.make("parent-thread");
const script = 'export const meta = { name: "test-workflow" };';
test.available.set(threadId, {
...v2Projection,
thread: {
...v2Projection.thread,
id: threadId,
creationSource: "provider",
lineage: {
rootThreadId: parentId,
parentThreadId: parentId,
relationshipToParent: "subagent",
},
},
messages: [
{
id: MessageId.make("script-message"),
threadId,
runId: null,
nodeId: null,
role: "user",
createdBy: "user",
creationSource: "provider",
text: script,
workflowScript: true,
attachments: [],
streaming: false,
createdAt: v2Projection.updatedAt,
updatedAt: v2Projection.updatedAt,
},
],
});
test.available.set(parentId, {
...v2Projection,
subagents: [
{
id: NodeId.make("coordinator"),
threadId: parentId,
runId: null,
parentNodeId: NodeId.make("parent-node"),
origin: "provider_native",
createdBy: "agent",
driver: ProviderDriverKind.make("codexAppServer"),
providerInstanceId: ProviderInstanceId.make("codex"),
providerThreadId: null,
nativeTaskRef: null,
childThreadId: threadId,
title: "Run test workflow",
prompt: script,
model: "test-model",
status: "running",
result: null,
startedAt: v2Projection.updatedAt,
completedAt: null,
updatedAt: v2Projection.updatedAt,
workflow: { name: "test-workflow", phases: [], agents: [] },
},
],
});
await test.render(true);
expect(test.loads).toEqual([threadId, parentId]);
expect(test.container.textContent).toBe(`test-workflow: ${script}`);
});
71 changes: 69 additions & 2 deletions apps/mobile/src/lib/filePreview.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { RegistryProvider } from "@effect/atom-react";
import { Atom } from "effect/reactivity";
import {
act,
createElement,
Expand All @@ -20,6 +22,8 @@ import { ThreadFeed } from "../features/threads/ThreadFeed";
import type { ThreadFeedEntry } from "./threadActivity";
import type { MarkdownImageRenderer } from "../native/SelectableMarkdownText";

const guestDetails = vi.hoisted(() => ({ read: vi.fn() }));

const audio = vi.hoisted(() => ({
status: {
playing: false,
Expand Down Expand Up @@ -166,11 +170,18 @@ vi.mock("../state/projects", () => ({
}));
vi.mock("../state/server", () => ({ serverEnvironment: {} }));
vi.mock("../state/session", () => ({
useEnvironmentScope: () => true,
readEnvironmentScope: () => true,
usePreparedConnection: () => ({ _tag: "Some", value: { httpBaseUrl: "https://example.com" } }),
}));
vi.mock("../state/atom-registry", () => ({ appAtomRegistry: {} }));
vi.mock("../state/threads", () => ({ environmentThreadShells: {}, threadEnvironment: {} }));
vi.mock("../state/threads", () => ({
environmentThreadShells: {},
threadEnvironment: {},
environmentThreadDetails: {
threadAtom: (ref: unknown) => guestDetails.read(ref) ?? Atom.make(null),
},
}));
vi.mock("../state/entities", () => ({
useLiveThreadLinkLabels: (text: string) => text,
useThreadChipIcons: () => new Map(),
Expand Down Expand Up @@ -269,7 +280,6 @@ vi.mock("./attachmentDownload", () => ({}));
vi.mock("./uuid", () => ({}));
vi.mock("../features/threads/thread-context-divider", () => ({}));
vi.mock("../features/threads/thread-handoff-row", () => ({}));
vi.mock("../features/threads/ThreadGuestShareBar", () => ({ useThreadGuestShare: () => null }));
vi.mock("../features/threads/SecretRequestCard", () => ({}));
vi.mock("../features/threads/LinkRequestCard", () => ({ LinkRequestCard: () => null }));
vi.mock("../features/threads/worktree-setup-card", () => ({}));
Expand Down Expand Up @@ -1419,3 +1429,60 @@ describe("ThreadFeed previews", () => {
}
});
});

it("does not read a newly created feed's guest details until creation completes", async () => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
const reads: string[] = [];
const threadAtom = Atom.family((id: string) =>
Atom.make(() => {
reads.push(id);
return null;
}),
);
guestDetails.read.mockImplementation((ref: { threadId: string }) => threadAtom(ref.threadId));
const container = document.createElement("div");
const root = createRoot(container);
const props: Parameters<typeof ThreadFeed>[0] = {
detailRef: null,
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("pending-thread"),
threadTitle: "pending",
feed: [],
queuedMessages: [],
dispatchingMessageId: null,
onEditPendingMessage: null,
contentPresentation: { kind: "ready" },
latestRun: null,
activeWorkStartedAt: null,
listRef: { current: null },
freeze: { value: false } as Parameters<typeof ThreadFeed>[0]["freeze"],
contentInsetEndAdjustment: { value: 0 } as Parameters<
typeof ThreadFeed
>[0]["contentInsetEndAdjustment"],
anchorMessageId: null,
keyboardOffset: 0,
};
try {
await act(async () =>
root.render(createElement(RegistryProvider, null, createElement(ThreadFeed, props))),
);
expect(reads).toEqual([]);
await act(async () =>
root.render(
createElement(
RegistryProvider,
null,
createElement(ThreadFeed, {
...props,
detailRef: { environmentId: props.environmentId, threadId: props.threadId },
}),
),
),
);
expect(reads).toEqual(["pending-thread"]);
} finally {
await act(async () => root.unmount());
guestDetails.read.mockReset();
vi.unstubAllGlobals();
}
});
1 change: 1 addition & 0 deletions apps/mobile/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { defineConfig, normalizePath } from "vite-plus";
import "vite-plus/test/config";

const reactTests = [
"src/features/threads/thread-workflow-opening.test.tsx",
"src/features/threads/git/GitBranchesSheet.occupancy.test.tsx",
"src/features/files/useFileTreeEntries.test.tsx",
"src/features/projects/AddProjectScreen.test.ts",
Expand Down
Loading