-
Notifications
You must be signed in to change notification settings - Fork 14.4k
Expand file tree
/
Copy pathGoalProperties.interactions.test.tsx
More file actions
317 lines (266 loc) · 9.32 KB
/
Copy pathGoalProperties.interactions.test.tsx
File metadata and controls
317 lines (266 loc) · 9.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// @vitest-environment jsdom
import type { ReactNode } from "react";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Agent, Goal } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { GoalProperties } from "./GoalProperties";
vi.mock("../context/CompanyContext", () => ({
useCompany: () => ({ selectedCompanyId: "company-1" }),
}));
const mockAgentsApi = vi.hoisted(() => ({
list: vi.fn(),
}));
const mockGoalsApi = vi.hoisted(() => ({
list: vi.fn(),
}));
vi.mock("../api/agents", () => ({
agentsApi: mockAgentsApi,
}));
vi.mock("../api/goals", () => ({
goalsApi: mockGoalsApi,
}));
vi.mock("@/lib/router", () => ({
Link: ({ children, to, ...props }: { children: ReactNode; to: string }) => (
<a href={to} {...props}>{children}</a>
),
}));
vi.mock("@/components/ui/separator", () => ({
Separator: () => <hr />,
}));
// Bypass Radix popover open/close mechanics: always render trigger + content.
vi.mock("@/components/ui/popover", () => ({
Popover: ({ children }: { children: ReactNode }) => <div>{children}</div>,
PopoverTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
PopoverContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));
vi.mock("./AgentIconPicker", () => ({
AgentIcon: () => null,
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
async function act(callback: () => void | Promise<void>) {
let result: void | Promise<void> = undefined;
flushSync(() => {
result = callback();
});
await result;
}
async function flush() {
await act(async () => {
await Promise.resolve();
await new Promise((resolve) => window.setTimeout(resolve, 0));
});
}
async function waitForAssertion(assertion: () => void, attempts = 20) {
let lastError: unknown;
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
assertion();
return;
} catch (error) {
lastError = error;
await flush();
}
}
throw lastError;
}
function makeGoal(overrides: Partial<Goal> = {}): Goal {
return {
id: "goal-1",
companyId: "company-1",
title: "Test Goal",
description: "Goal description",
level: "task",
status: "planned",
parentId: null,
ownerAgentId: null,
createdAt: new Date("2026-01-01T00:00:00Z"),
updatedAt: new Date("2026-01-01T00:00:00Z"),
...overrides,
};
}
function makeAgent(overrides: Partial<Agent> = {}): Agent {
return {
id: "agent-1",
companyId: "company-1",
name: "Alpha Agent",
urlKey: "alpha",
role: "engineer",
title: null,
icon: null,
status: "active",
reportsTo: null,
capabilities: null,
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
budgetMonthlyCents: 0,
spentMonthlyCents: 0,
pauseReason: null,
pausedAt: null,
permissions: { canCreateAgents: false },
lastHeartbeatAt: null,
metadata: null,
createdAt: new Date("2026-01-01T00:00:00Z"),
updatedAt: new Date("2026-01-01T00:00:00Z"),
...overrides,
};
}
function findButtonByText(root: HTMLElement, text: string): HTMLButtonElement | undefined {
return Array.from(root.querySelectorAll("button")).find((b) => b.textContent?.trim() === text);
}
describe("GoalProperties interactions", () => {
let container: HTMLDivElement;
let root: ReturnType<typeof createRoot> | null;
let queryClient: QueryClient;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = null;
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockAgentsApi.list.mockResolvedValue([
makeAgent({ id: "agent-1", name: "Alpha Agent" }),
makeAgent({ id: "agent-2", name: "Beta Agent" }),
]);
mockGoalsApi.list.mockResolvedValue([]);
});
afterEach(async () => {
const currentRoot = root;
if (currentRoot) {
await act(async () => {
currentRoot.unmount();
});
}
queryClient.clear();
container.remove();
document.body.innerHTML = "";
vi.clearAllMocks();
});
function render(props: Partial<Parameters<typeof GoalProperties>[0]> & { goal: Goal }) {
root = createRoot(container);
root.render(
<QueryClientProvider client={queryClient}>
<GoalProperties {...props} />
</QueryClientProvider>,
);
}
describe("delete confirmation flow", () => {
it("requires a confirmation step before calling onDelete", async () => {
const onDelete = vi.fn();
render({ goal: makeGoal(), onUpdate: () => {}, onDelete });
await flush();
expect(container.textContent).not.toContain("This action cannot be undone");
expect(onDelete).not.toHaveBeenCalled();
const deleteTrigger = findButtonByText(container, "Delete Goal");
expect(deleteTrigger).toBeTruthy();
await act(async () => {
deleteTrigger?.click();
});
await flush();
expect(container.textContent).toContain("This action cannot be undone");
expect(onDelete).not.toHaveBeenCalled();
const confirmButton = findButtonByText(container, "Confirm Delete");
await act(async () => {
confirmButton?.click();
});
await flush();
expect(onDelete).toHaveBeenCalledTimes(1);
});
it("cancels out of the confirmation step without calling onDelete", async () => {
const onDelete = vi.fn();
render({ goal: makeGoal(), onUpdate: () => {}, onDelete });
await flush();
await act(async () => {
findButtonByText(container, "Delete Goal")?.click();
});
await flush();
expect(container.textContent).toContain("This action cannot be undone");
await act(async () => {
findButtonByText(container, "Cancel")?.click();
});
await flush();
expect(container.textContent).not.toContain("This action cannot be undone");
expect(onDelete).not.toHaveBeenCalled();
});
it("disables confirm/cancel buttons and shows pending state while deleting", async () => {
const onDelete = vi.fn();
render({ goal: makeGoal(), onUpdate: () => {}, onDelete, deletePending: true });
await flush();
await act(async () => {
findButtonByText(container, "Delete Goal")?.click();
});
await flush();
const deletingButton = findButtonByText(container, "Deleting...");
expect(deletingButton).toBeTruthy();
expect(deletingButton?.disabled).toBe(true);
});
it("surfaces a delete error message inside the confirmation panel", async () => {
const onDelete = vi.fn();
render({
goal: makeGoal(),
onUpdate: () => {},
onDelete,
deleteError: "Cannot delete a goal with linked issues",
});
await flush();
await act(async () => {
findButtonByText(container, "Delete Goal")?.click();
});
await flush();
expect(container.textContent).toContain("Cannot delete a goal with linked issues");
const alert = container.querySelector('[role="alert"]');
expect(alert?.textContent).toContain("Cannot delete a goal with linked issues");
});
it("does not render the delete action when onDelete is not provided", async () => {
render({ goal: makeGoal(), onUpdate: () => {} });
await flush();
expect(findButtonByText(container, "Delete Goal")).toBeUndefined();
});
});
describe("owner reassignment", () => {
it("calls onUpdate with the selected agent id when an owner is chosen", async () => {
const onUpdate = vi.fn();
render({ goal: makeGoal({ ownerAgentId: null }), onUpdate });
await flush();
let betaOption: HTMLButtonElement | undefined;
await waitForAssertion(() => {
betaOption = findButtonByText(container, "Beta Agent");
expect(betaOption).toBeTruthy();
});
await act(async () => {
betaOption?.click();
});
await flush();
expect(onUpdate).toHaveBeenCalledWith({ ownerAgentId: "agent-2" });
});
it("calls onUpdate with null when the owner is cleared", async () => {
const onUpdate = vi.fn();
render({ goal: makeGoal({ ownerAgentId: "agent-1" }), onUpdate });
await flush();
// Wait for the agents list to resolve so the trigger reflects the
// current owner ("Alpha Agent") rather than the "None" loading
// fallback — otherwise both the trigger and the clear option would
// read "None" and the wrong button could be targeted.
await waitForAssertion(() => {
expect(container.textContent).toContain("Alpha Agent");
});
const noneOption = findButtonByText(container, "None");
expect(noneOption).toBeTruthy();
await act(async () => {
noneOption?.click();
});
await flush();
expect(onUpdate).toHaveBeenCalledWith({ ownerAgentId: null });
});
it("renders the owner as a read-only link when onUpdate is not provided", async () => {
render({ goal: makeGoal({ ownerAgentId: "agent-1" }) });
await flush();
await waitForAssertion(() => {
expect(container.querySelector("a[href]")).toBeTruthy();
expect(container.textContent).toContain("Alpha Agent");
});
});
});
});