mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 02:30:43 +01:00
Merge master into Speko UI and reconcile Storybook catalog
This commit is contained in:
commit
e61e19d0dc
1564 files changed
+208511
-127704
No files matched your search
@@ -262,6 +262,46 @@ function setInputValue(input: HTMLInputElement, value: string) {
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
|
||||
function daytonaEnvironments() {
|
||||
return [
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "Daytona",
|
||||
driver: "sandbox",
|
||||
config: { provider: "daytona" },
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
function e2bEnvironments() {
|
||||
return [
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "E2B",
|
||||
driver: "sandbox",
|
||||
config: { provider: "e2b" },
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
function renderFormView(root: Root, queryClient: QueryClient, children: Parameters<Root["render"]>[0]) {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>{children}</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
function createFormQueryClient() {
|
||||
return new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
}
|
||||
|
||||
async function renderForm(
|
||||
environments: Environment[],
|
||||
agentOverrides: Partial<Agent> = {},
|
||||
@@ -281,35 +321,24 @@ async function renderForm(
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const onSave = vi.fn();
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<AgentConfigForm
|
||||
mode="edit"
|
||||
agent={makeAgent(agentOverrides)}
|
||||
onSave={onSave}
|
||||
hidePromptTemplate
|
||||
content={options.content}
|
||||
environmentVariablesPlacement={options.environmentVariablesPlacement}
|
||||
hideInlineSave={options.hideInlineSave}
|
||||
onDirtyChange={options.onDirtyChange}
|
||||
onSaveActionChange={options.onSaveActionChange}
|
||||
onCancelActionChange={options.onCancelActionChange}
|
||||
showAdapterTypeField={false}
|
||||
showAdapterTestEnvironmentButton={options.showAdapterTestEnvironmentButton ?? false}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
renderFormView(root, queryClient,
|
||||
<AgentConfigForm
|
||||
mode="edit"
|
||||
agent={makeAgent(agentOverrides)}
|
||||
onSave={onSave}
|
||||
hidePromptTemplate
|
||||
content={options.content}
|
||||
environmentVariablesPlacement={options.environmentVariablesPlacement}
|
||||
hideInlineSave={options.hideInlineSave}
|
||||
onDirtyChange={options.onDirtyChange}
|
||||
onSaveActionChange={options.onSaveActionChange}
|
||||
onCancelActionChange={options.onCancelActionChange}
|
||||
showAdapterTypeField={false}
|
||||
showAdapterTestEnvironmentButton={options.showAdapterTestEnvironmentButton ?? false}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -327,12 +356,7 @@ async function renderCreateForm(
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
|
||||
const values = {
|
||||
...defaultCreateValues,
|
||||
@@ -342,21 +366,15 @@ async function renderCreateForm(
|
||||
const onChange = vi.fn();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<AgentConfigForm
|
||||
mode="create"
|
||||
values={values}
|
||||
onChange={onChange}
|
||||
hidePromptTemplate
|
||||
showAdapterTypeField={false}
|
||||
showAdapterTestEnvironmentButton={options.showAdapterTestEnvironmentButton ?? false}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
renderFormView(root, queryClient,
|
||||
<AgentConfigForm
|
||||
mode="create"
|
||||
values={values}
|
||||
onChange={onChange}
|
||||
hidePromptTemplate
|
||||
showAdapterTypeField={false}
|
||||
showAdapterTestEnvironmentButton={options.showAdapterTestEnvironmentButton ?? false}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -461,15 +479,7 @@ function findByAriaLabel(container: HTMLElement, label: string) {
|
||||
|
||||
async function renderCodexSandbox(agentOverrides: Partial<Agent> = {}) {
|
||||
return renderForm(
|
||||
[
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "Daytona",
|
||||
driver: "sandbox",
|
||||
config: { provider: "daytona" },
|
||||
}),
|
||||
],
|
||||
daytonaEnvironments(),
|
||||
{ defaultEnvironmentId: "sandbox-1", ...agentOverrides },
|
||||
{ showAdapterTestEnvironmentButton: true },
|
||||
);
|
||||
@@ -480,15 +490,7 @@ async function renderCodexSandbox(agentOverrides: Partial<Agent> = {}) {
|
||||
// provider advertises the login pseudo-terminal capability the login needs.
|
||||
async function renderVendorSandbox(agentOverrides: Partial<Agent> = {}) {
|
||||
return renderForm(
|
||||
[
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "Daytona",
|
||||
driver: "sandbox",
|
||||
config: { provider: "daytona" },
|
||||
}),
|
||||
],
|
||||
daytonaEnvironments(),
|
||||
{ adapterType: "vendor_local", defaultEnvironmentId: "sandbox-1", ...agentOverrides },
|
||||
{ showAdapterTestEnvironmentButton: true },
|
||||
);
|
||||
@@ -500,15 +502,7 @@ async function renderVendorSandbox(agentOverrides: Partial<Agent> = {}) {
|
||||
// login needs.
|
||||
async function renderGrokSandbox(agentOverrides: Partial<Agent> = {}) {
|
||||
return renderForm(
|
||||
[
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "Daytona",
|
||||
driver: "sandbox",
|
||||
config: { provider: "daytona" },
|
||||
}),
|
||||
],
|
||||
daytonaEnvironments(),
|
||||
{ adapterType: "grok_local", defaultEnvironmentId: "sandbox-1", ...agentOverrides },
|
||||
{ showAdapterTestEnvironmentButton: true },
|
||||
);
|
||||
@@ -516,15 +510,7 @@ async function renderGrokSandbox(agentOverrides: Partial<Agent> = {}) {
|
||||
|
||||
async function renderClaudeSandbox(agentOverrides: Partial<Agent> = {}) {
|
||||
return renderForm(
|
||||
[
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "Daytona",
|
||||
driver: "sandbox",
|
||||
config: { provider: "daytona" },
|
||||
}),
|
||||
],
|
||||
daytonaEnvironments(),
|
||||
{ adapterType: "claude_local", defaultEnvironmentId: "sandbox-1", ...agentOverrides },
|
||||
{ showAdapterTestEnvironmentButton: true },
|
||||
);
|
||||
@@ -534,15 +520,7 @@ async function renderCreateClaudeSandbox(
|
||||
valueOverrides: Partial<typeof defaultCreateValues> = {},
|
||||
) {
|
||||
return renderCreateForm(
|
||||
[
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "Daytona",
|
||||
driver: "sandbox",
|
||||
config: { provider: "daytona" },
|
||||
}),
|
||||
],
|
||||
daytonaEnvironments(),
|
||||
{ adapterType: "claude_local", defaultEnvironmentId: "sandbox-1", ...valueOverrides },
|
||||
{ showAdapterTestEnvironmentButton: true },
|
||||
);
|
||||
@@ -560,9 +538,7 @@ async function renderStatefulCreateClaudeSandbox(environments: Environment[]) {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
|
||||
const valuesRef: { current: typeof defaultCreateValues } = {
|
||||
current: {
|
||||
@@ -588,15 +564,7 @@ async function renderStatefulCreateClaudeSandbox(environments: Environment[]) {
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<Harness />
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
renderFormView(root, queryClient, <Harness />);
|
||||
});
|
||||
|
||||
await flushReact();
|
||||
@@ -967,15 +935,7 @@ describe("AgentConfigForm environment selector", () => {
|
||||
});
|
||||
|
||||
it("shows concise Environment copy when one runnable non-local environment exists", async () => {
|
||||
const result = await renderForm([
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "E2B",
|
||||
driver: "sandbox",
|
||||
config: { provider: "e2b" },
|
||||
}),
|
||||
]);
|
||||
const result = await renderForm(e2bEnvironments());
|
||||
roots.push(result.root);
|
||||
|
||||
const text = result.container.textContent ?? "";
|
||||
@@ -992,15 +952,7 @@ describe("AgentConfigForm environment selector", () => {
|
||||
|
||||
it("shows the environment override for Grok local agents", async () => {
|
||||
const result = await renderForm(
|
||||
[
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "E2B",
|
||||
driver: "sandbox",
|
||||
config: { provider: "e2b" },
|
||||
}),
|
||||
],
|
||||
e2bEnvironments(),
|
||||
{ adapterType: "grok_local" },
|
||||
);
|
||||
roots.push(result.root);
|
||||
@@ -1014,15 +966,7 @@ describe("AgentConfigForm environment selector", () => {
|
||||
|
||||
it("shows the environment override for Kimi local agents", async () => {
|
||||
const result = await renderForm(
|
||||
[
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "E2B",
|
||||
driver: "sandbox",
|
||||
config: { provider: "e2b" },
|
||||
}),
|
||||
],
|
||||
e2bEnvironments(),
|
||||
{ adapterType: "kimi_local" },
|
||||
);
|
||||
roots.push(result.root);
|
||||
@@ -1265,15 +1209,7 @@ describe("AgentConfigForm environment selector", () => {
|
||||
// no capability, so the panel stays hidden even after the auth-missing check.
|
||||
mockAgentsApi.testEnvironment.mockResolvedValue(AUTH_MISSING_RESULT);
|
||||
const result = await renderForm(
|
||||
[
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "E2B",
|
||||
driver: "sandbox",
|
||||
config: { provider: "e2b" },
|
||||
}),
|
||||
],
|
||||
e2bEnvironments(),
|
||||
{ adapterType: "codex_local", defaultEnvironmentId: "sandbox-1" },
|
||||
{ showAdapterTestEnvironmentButton: true },
|
||||
);
|
||||
@@ -1344,15 +1280,7 @@ describe("AgentConfigForm environment selector", () => {
|
||||
it("hides the Login button for a Claude sandbox whose provider lacks the setup-token login capability", async () => {
|
||||
mockAgentsApi.testEnvironment.mockResolvedValue(CLAUDE_AUTH_MISSING_RESULT);
|
||||
const result = await renderForm(
|
||||
[
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "E2B",
|
||||
driver: "sandbox",
|
||||
config: { provider: "e2b" },
|
||||
}),
|
||||
],
|
||||
e2bEnvironments(),
|
||||
{ adapterType: "claude_local", defaultEnvironmentId: "sandbox-1" },
|
||||
{ showAdapterTestEnvironmentButton: true },
|
||||
);
|
||||
@@ -1381,15 +1309,7 @@ describe("AgentConfigForm environment selector", () => {
|
||||
}),
|
||||
);
|
||||
const result = await renderForm(
|
||||
[
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "Daytona",
|
||||
driver: "sandbox",
|
||||
config: { provider: "daytona" },
|
||||
}),
|
||||
],
|
||||
daytonaEnvironments(),
|
||||
{ adapterType: "claude_local", defaultEnvironmentId: "sandbox-1" },
|
||||
{ showAdapterTestEnvironmentButton: true },
|
||||
);
|
||||
@@ -1407,15 +1327,7 @@ describe("AgentConfigForm environment selector", () => {
|
||||
// after the auth-missing check.
|
||||
mockAgentsApi.testEnvironment.mockResolvedValue(PTY_VENDOR_AUTH_MISSING_RESULT);
|
||||
const result = await renderForm(
|
||||
[
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "E2B",
|
||||
driver: "sandbox",
|
||||
config: { provider: "e2b" },
|
||||
}),
|
||||
],
|
||||
e2bEnvironments(),
|
||||
{ adapterType: "pty_vendor_local", defaultEnvironmentId: "sandbox-1" },
|
||||
{ showAdapterTestEnvironmentButton: true },
|
||||
);
|
||||
@@ -1432,15 +1344,7 @@ describe("AgentConfigForm environment selector", () => {
|
||||
// provider capability, not the adapter name.
|
||||
mockAgentsApi.testEnvironment.mockResolvedValue(PTY_VENDOR_AUTH_MISSING_RESULT);
|
||||
const result = await renderForm(
|
||||
[
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "Daytona",
|
||||
driver: "sandbox",
|
||||
config: { provider: "daytona" },
|
||||
}),
|
||||
],
|
||||
daytonaEnvironments(),
|
||||
{ adapterType: "pty_vendor_local", defaultEnvironmentId: "sandbox-1" },
|
||||
{ showAdapterTestEnvironmentButton: true },
|
||||
);
|
||||
@@ -1457,23 +1361,13 @@ describe("AgentConfigForm environment selector", () => {
|
||||
// lifts the feedback and renders `AdapterLoginPanel` from the lifted login
|
||||
// descriptor. Without the descriptor the Login button never appears.
|
||||
mockAgentsApi.testEnvironment.mockResolvedValue(AUTH_MISSING_RESULT);
|
||||
mockEnvironmentsApi.list.mockResolvedValue([
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "Daytona",
|
||||
driver: "sandbox",
|
||||
config: { provider: "daytona" },
|
||||
}),
|
||||
]);
|
||||
mockEnvironmentsApi.list.mockResolvedValue(daytonaEnvironments());
|
||||
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
roots.push(root);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
|
||||
function LiftedFeedbackHarness() {
|
||||
const [login, setLogin] = useState<AdapterLoginDescriptor | null>(null);
|
||||
@@ -1504,15 +1398,7 @@ describe("AgentConfigForm environment selector", () => {
|
||||
}
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<LiftedFeedbackHarness />
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
renderFormView(root, queryClient, <LiftedFeedbackHarness />);
|
||||
});
|
||||
await flushReact();
|
||||
|
||||
@@ -1777,12 +1663,12 @@ describe("AgentConfigForm environment selector", () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container); roots.push(root);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
||||
const queryClient = createFormQueryClient();
|
||||
await act(async () => {
|
||||
root.render(<QueryClientProvider client={queryClient}><ToastProvider><TooltipProvider>
|
||||
renderFormView(root, queryClient,
|
||||
<AdapterLoginPanel companyId="company-1" adapterType="grok_local" environmentId="new-sandbox"
|
||||
aiConnection={{ ...intent, agentIds: [] }} chrome="onboarding" autoStart />
|
||||
</TooltipProvider></ToastProvider></QueryClientProvider>);
|
||||
aiConnection={{ ...intent, agentIds: [] }} chrome="onboarding" autoStart />
|
||||
);
|
||||
});
|
||||
await flushUntil(() => Boolean(findButton(container, "Cancel previous sign-in and retry")));
|
||||
expect(mockAgentsApi.startAdapterAuthLogin).not.toHaveBeenCalled();
|
||||
@@ -1814,25 +1700,17 @@ describe("AgentConfigForm environment selector", () => {
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
roots.push(root);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="codex_local"
|
||||
environmentId="sandbox-1"
|
||||
chrome="onboarding"
|
||||
autoStart
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
renderFormView(root, queryClient,
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="codex_local"
|
||||
environmentId="sandbox-1"
|
||||
chrome="onboarding"
|
||||
autoStart
|
||||
/>
|
||||
);
|
||||
});
|
||||
// Wait for the card itself, then assert it is actually there: an absence
|
||||
@@ -1869,25 +1747,17 @@ describe("AgentConfigForm environment selector", () => {
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
roots.push(root);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="codex_local"
|
||||
environmentId="sandbox-1"
|
||||
autoStart
|
||||
onAccountBinding={onAccountBinding}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
renderFormView(root, queryClient,
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="codex_local"
|
||||
environmentId="sandbox-1"
|
||||
autoStart
|
||||
onAccountBinding={onAccountBinding}
|
||||
/>
|
||||
);
|
||||
});
|
||||
await flushUntil(() => onAccountBinding.mock.calls.length > 0);
|
||||
@@ -1900,6 +1770,7 @@ describe("AgentConfigForm environment selector", () => {
|
||||
// The panel narrates the bind as its own state, separate from the login's
|
||||
// success line — the bind is a second save that can still fail.
|
||||
await flushUntil(() => container.textContent?.includes("Agent bound to the signed-in account") ?? false);
|
||||
expect(container.textContent).toContain("Agent bound to the signed-in account");
|
||||
});
|
||||
|
||||
it("a failed bind save renders an explicit Retry instead of silently latching the claim", async () => {
|
||||
@@ -1931,25 +1802,17 @@ describe("AgentConfigForm environment selector", () => {
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
roots.push(root);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="codex_local"
|
||||
environmentId="sandbox-1"
|
||||
autoStart
|
||||
onAccountBinding={onAccountBinding}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
renderFormView(root, queryClient,
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="codex_local"
|
||||
environmentId="sandbox-1"
|
||||
autoStart
|
||||
onAccountBinding={onAccountBinding}
|
||||
/>
|
||||
);
|
||||
});
|
||||
await flushUntil(() => container.textContent?.includes("Could not bind this agent") ?? false);
|
||||
@@ -2007,25 +1870,17 @@ describe("AgentConfigForm environment selector", () => {
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
roots.push(root);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="codex_local"
|
||||
environmentId="sandbox-1"
|
||||
autoStart
|
||||
onAccountBinding={onAccountBinding}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
renderFormView(root, queryClient,
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="codex_local"
|
||||
environmentId="sandbox-1"
|
||||
autoStart
|
||||
onAccountBinding={onAccountBinding}
|
||||
/>
|
||||
);
|
||||
});
|
||||
await flushUntil(() => onAccountBinding.mock.calls.length === 1);
|
||||
@@ -2079,25 +1934,17 @@ describe("AgentConfigForm environment selector", () => {
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
roots.push(root);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="codex_local"
|
||||
environmentId="sandbox-1"
|
||||
autoStart
|
||||
onAccountBinding={onAccountBinding}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
renderFormView(root, queryClient,
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="codex_local"
|
||||
environmentId="sandbox-1"
|
||||
autoStart
|
||||
onAccountBinding={onAccountBinding}
|
||||
/>
|
||||
);
|
||||
});
|
||||
await flushUntil(() => container.textContent?.includes("Binding this agent") ?? false);
|
||||
@@ -2130,7 +1977,7 @@ describe("AgentConfigForm environment selector", () => {
|
||||
<AgentConfigForm mode="edit" agent={saved} onSave={onSave} hidePromptTemplate showAdapterTypeField={false} />
|
||||
</>;
|
||||
}
|
||||
await act(async () => root.render(<QueryClientProvider client={queryClient}><ToastProvider><TooltipProvider><Harness /></TooltipProvider></ToastProvider></QueryClientProvider>));
|
||||
await act(async () => renderFormView(root, queryClient, <Harness />));
|
||||
await flushReact();
|
||||
const nameInput = container.querySelector<HTMLInputElement>('input[placeholder="Agent name"]')!;
|
||||
setInputValue(nameInput, "Unsaved name");
|
||||
@@ -2182,23 +2029,13 @@ describe("AgentConfigForm environment selector", () => {
|
||||
releaseSaves.push(resolve);
|
||||
}),
|
||||
);
|
||||
mockEnvironmentsApi.list.mockResolvedValue([
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "Daytona",
|
||||
driver: "sandbox",
|
||||
config: { provider: "daytona" },
|
||||
}),
|
||||
]);
|
||||
mockEnvironmentsApi.list.mockResolvedValue(daytonaEnvironments());
|
||||
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
roots.push(root);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
|
||||
// The harness swaps the agent object the way the page does after a save
|
||||
// refresh: same mounted form, new agent identity.
|
||||
@@ -2218,15 +2055,7 @@ describe("AgentConfigForm environment selector", () => {
|
||||
);
|
||||
}
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<RefreshHarness />
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
renderFormView(root, queryClient, <RefreshHarness />);
|
||||
});
|
||||
await flushReact();
|
||||
|
||||
@@ -2733,15 +2562,7 @@ describe("AgentConfigForm environment selector", () => {
|
||||
.mockResolvedValueOnce(staleList)
|
||||
.mockResolvedValue(freshList);
|
||||
|
||||
const result = await renderStatefulCreateClaudeSandbox([
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "Daytona",
|
||||
driver: "sandbox",
|
||||
config: { provider: "daytona" },
|
||||
}),
|
||||
]);
|
||||
const result = await renderStatefulCreateClaudeSandbox(daytonaEnvironments());
|
||||
roots.push(result.root);
|
||||
|
||||
await runTest(result.container);
|
||||
@@ -2781,24 +2602,16 @@ describe("AgentConfigForm environment selector", () => {
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
roots.push(root);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="claude_local"
|
||||
environmentId="sandbox-1"
|
||||
onStored={onStored}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
renderFormView(root, queryClient,
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="claude_local"
|
||||
environmentId="sandbox-1"
|
||||
onStored={onStored}
|
||||
/>
|
||||
);
|
||||
});
|
||||
await startLogin(container);
|
||||
@@ -2818,25 +2631,17 @@ describe("AgentConfigForm environment selector", () => {
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
roots.push(root);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="claude_local"
|
||||
environmentId="sandbox-1"
|
||||
chrome="onboarding"
|
||||
autoStart
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
renderFormView(root, queryClient,
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="claude_local"
|
||||
environmentId="sandbox-1"
|
||||
chrome="onboarding"
|
||||
autoStart
|
||||
/>
|
||||
);
|
||||
});
|
||||
// Wait for the card itself, then assert it is actually there: an absence
|
||||
@@ -2858,24 +2663,16 @@ describe("AgentConfigForm environment selector", () => {
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
roots.push(root);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="claude_local"
|
||||
environmentId="sandbox-1"
|
||||
onApplyStored={onApplyStored}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
renderFormView(root, queryClient,
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="claude_local"
|
||||
environmentId="sandbox-1"
|
||||
onApplyStored={onApplyStored}
|
||||
/>
|
||||
);
|
||||
});
|
||||
await flushUntil(() => Boolean(findButton(container, "Use saved login")));
|
||||
@@ -2900,24 +2697,16 @@ describe("AgentConfigForm environment selector", () => {
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
roots.push(root);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="claude_local"
|
||||
environmentId="sandbox-1"
|
||||
onApplyStored={onApplyStored}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
renderFormView(root, queryClient,
|
||||
<AdapterLoginPanel
|
||||
companyId="company-1"
|
||||
adapterType="claude_local"
|
||||
environmentId="sandbox-1"
|
||||
onApplyStored={onApplyStored}
|
||||
/>
|
||||
);
|
||||
});
|
||||
await flushUntil(() => Boolean(findButton(container, "Sign in")));
|
||||
@@ -3305,42 +3094,26 @@ describe("AgentConfigForm environment selector", () => {
|
||||
await flushFake();
|
||||
};
|
||||
|
||||
mockEnvironmentsApi.list.mockResolvedValue([
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "Daytona",
|
||||
driver: "sandbox",
|
||||
config: { provider: "daytona" },
|
||||
}),
|
||||
]);
|
||||
mockEnvironmentsApi.list.mockResolvedValue(daytonaEnvironments());
|
||||
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
roots.push(root);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<AgentConfigForm
|
||||
mode="edit"
|
||||
agent={makeAgent({
|
||||
adapterType: "claude_local",
|
||||
defaultEnvironmentId: "sandbox-1",
|
||||
})}
|
||||
onSave={vi.fn()}
|
||||
hidePromptTemplate
|
||||
showAdapterTypeField={false}
|
||||
showAdapterTestEnvironmentButton
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
renderFormView(root, queryClient,
|
||||
<AgentConfigForm
|
||||
mode="edit"
|
||||
agent={makeAgent({
|
||||
adapterType: "claude_local",
|
||||
defaultEnvironmentId: "sandbox-1",
|
||||
})}
|
||||
onSave={vi.fn()}
|
||||
hidePromptTemplate
|
||||
showAdapterTypeField={false}
|
||||
showAdapterTestEnvironmentButton
|
||||
/>
|
||||
);
|
||||
});
|
||||
await flushFake();
|
||||
@@ -3627,44 +3400,28 @@ describe("AgentConfigForm create-mode Claude OAuth binding", () => {
|
||||
// environment. The helper returns the `onSave` spy so a test can read the patch
|
||||
// that a stored login sends to the agent-update path.
|
||||
async function renderEditClaudeSandbox(agentOverrides: Partial<Agent> = {}) {
|
||||
mockEnvironmentsApi.list.mockResolvedValue([
|
||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||
makeEnvironment({
|
||||
id: "sandbox-1",
|
||||
name: "Daytona",
|
||||
driver: "sandbox",
|
||||
config: { provider: "daytona" },
|
||||
}),
|
||||
]);
|
||||
mockEnvironmentsApi.list.mockResolvedValue(daytonaEnvironments());
|
||||
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
const queryClient = createFormQueryClient();
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider>
|
||||
<AgentConfigForm
|
||||
mode="edit"
|
||||
agent={makeAgent({
|
||||
adapterType: "claude_local",
|
||||
defaultEnvironmentId: "sandbox-1",
|
||||
...agentOverrides,
|
||||
})}
|
||||
onSave={onSave}
|
||||
hidePromptTemplate
|
||||
showAdapterTypeField={false}
|
||||
showAdapterTestEnvironmentButton
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>,
|
||||
renderFormView(root, queryClient,
|
||||
<AgentConfigForm
|
||||
mode="edit"
|
||||
agent={makeAgent({
|
||||
adapterType: "claude_local",
|
||||
defaultEnvironmentId: "sandbox-1",
|
||||
...agentOverrides,
|
||||
})}
|
||||
onSave={onSave}
|
||||
hidePromptTemplate
|
||||
showAdapterTypeField={false}
|
||||
showAdapterTestEnvironmentButton
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useMemo } from "react";
|
||||
import type { CostByBiller, CostByProviderModel } from "@paperclipai/shared";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { QuotaBar } from "./QuotaBar";
|
||||
import { CostAmount } from "./CostAmount";
|
||||
import { billingTypeDisplayName, formatCents, formatTokens, providerDisplayName } from "@/lib/utils";
|
||||
|
||||
interface BillerSpendCardProps {
|
||||
@@ -71,9 +72,10 @@ export function BillerSpendCard({
|
||||
{row.modelCount} model{row.modelCount === 1 ? "" : "s"}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<span className="text-xl font-bold tabular-nums shrink-0">
|
||||
{formatCents(row.costCents)}
|
||||
</span>
|
||||
<div className="text-xl shrink-0">
|
||||
<CostAmount costCents={row.costCents} eventCount={row.eventCount}
|
||||
estimatedEventCount={row.estimatedEventCount} unpricedEventCount={row.unpricedEventCount} showUnavailableCount />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
|
||||
@@ -76,10 +76,13 @@ export function BlockedInboxView({
|
||||
error,
|
||||
refetch,
|
||||
} = useQuery({
|
||||
queryKey: [...queryKeys.issues.listBlockedAttention(companyId), "live-descendant-summary"],
|
||||
queryKey: [...queryKeys.issues.listBlockedAttention(companyId), "live-descendant-summary", issueFilters.showAgentCreatedTasks],
|
||||
queryFn: () =>
|
||||
issuesApi.list(companyId, {
|
||||
attention: "blocked",
|
||||
includeRoutineExecutions: true,
|
||||
includeAgentCreatedTasks: issueFilters.showAgentCreatedTasks,
|
||||
includeParticipatedTasks: true,
|
||||
includeBlockedInboxAttention: true,
|
||||
includeBlockedBy: true,
|
||||
includeLiveDescendantSummary: true,
|
||||
@@ -98,7 +101,7 @@ export function BlockedInboxView({
|
||||
filteredRows.map((row) => row.issue),
|
||||
issueFilters,
|
||||
currentUserId,
|
||||
true,
|
||||
false,
|
||||
liveIssueIds,
|
||||
workspaceFilterContext,
|
||||
).map((issue) => issue.id),
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import type { BudgetIncident } from "@paperclipai/shared";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { BudgetIncidentCard } from "./BudgetIncidentCard";
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
function incident(overrides: Partial<BudgetIncident> = {}): BudgetIncident {
|
||||
return {
|
||||
id: "incident-1",
|
||||
companyId: "company-1",
|
||||
policyId: "policy-1",
|
||||
scopeType: "agent",
|
||||
scopeId: "agent-1",
|
||||
scopeName: "Budget Demo",
|
||||
metric: "billed_cents",
|
||||
windowKind: "calendar_month_utc",
|
||||
windowStart: new Date("2026-10-01T00:00:00Z"),
|
||||
windowEnd: new Date("2026-11-01T00:00:00Z"),
|
||||
thresholdType: "hard",
|
||||
amountLimit: 100_000,
|
||||
amountObserved: 100_000,
|
||||
status: "open",
|
||||
approvalId: null,
|
||||
approvalStatus: null,
|
||||
resolvedAt: null,
|
||||
createdAt: new Date("2026-10-12T00:00:00Z"),
|
||||
updatedAt: new Date("2026-10-12T00:00:00Z"),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function renderCard(value: BudgetIncident) {
|
||||
const div = document.createElement("div");
|
||||
document.body.append(div);
|
||||
const root = createRoot(div);
|
||||
const onKeepPaused = vi.fn();
|
||||
const onRaiseAndResume = vi.fn();
|
||||
await act(async () => root.render(
|
||||
<BudgetIncidentCard incident={value} onKeepPaused={onKeepPaused} onRaiseAndResume={onRaiseAndResume} />,
|
||||
));
|
||||
const buttons = () => Array.from(div.querySelectorAll("button"), (button) => button.textContent?.trim());
|
||||
return {
|
||||
div,
|
||||
buttons,
|
||||
onKeepPaused,
|
||||
cleanup: async () => {
|
||||
await act(async () => root.unmount());
|
||||
div.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("BudgetIncidentCard", () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it("labels a hard-stop incident as paused", async () => {
|
||||
const { div, buttons, cleanup } = await renderCard(incident());
|
||||
expect(div.textContent).toContain("agent hard stop");
|
||||
expect(div.textContent).toContain("This scope is paused.");
|
||||
expect(buttons()).toEqual(["Raise budget & resume", "Keep paused"]);
|
||||
expect(div.querySelector("input")?.value).toBe("1010.00");
|
||||
await cleanup();
|
||||
});
|
||||
|
||||
it("labels a soft-threshold incident as a warning that does not pause the scope", async () => {
|
||||
const { div, buttons, onKeepPaused, cleanup } = await renderCard(
|
||||
incident({ thresholdType: "soft", amountObserved: 80_000 }),
|
||||
);
|
||||
expect(div.textContent).toContain("agent budget warning");
|
||||
expect(div.textContent).not.toContain("hard stop");
|
||||
expect(div.textContent).not.toContain("paused");
|
||||
expect(div.textContent).toContain("This warning does not pause work.");
|
||||
expect(div.textContent).toContain("Spending reached $800.00 against a limit of $1,000.00.");
|
||||
expect(buttons()).toEqual(["Raise budget", "Dismiss warning"]);
|
||||
expect(div.querySelector("input")?.value).toBe("1010.00");
|
||||
const dismiss = Array.from(div.querySelectorAll("button")).find((button) => button.textContent?.trim() === "Dismiss warning")!;
|
||||
await act(async () => dismiss.click());
|
||||
expect(onKeepPaused).toHaveBeenCalledTimes(1);
|
||||
await cleanup();
|
||||
});
|
||||
|
||||
it("describes a paused project for a project hard stop", async () => {
|
||||
const { div, cleanup } = await renderCard(incident({ scopeType: "project", scopeName: "Website" }));
|
||||
expect(div.textContent).toContain("project hard stop");
|
||||
expect(div.textContent).toContain("Project execution is paused.");
|
||||
await cleanup();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import type { BudgetIncident } from "@paperclipai/shared";
|
||||
import { AlertOctagon, ArrowUpRight, PauseCircle } from "lucide-react";
|
||||
import { AlertOctagon, AlertTriangle, ArrowUpRight, PauseCircle } from "lucide-react";
|
||||
import { formatCents } from "../lib/utils";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -36,46 +36,66 @@ export function BudgetIncidentCard({
|
||||
onKeepPaused: () => void;
|
||||
isMutating?: boolean;
|
||||
}) {
|
||||
const isWarning = incident.thresholdType === "soft";
|
||||
const [draftAmount, setDraftAmount] = useState(
|
||||
centsInputValue(Math.max(incident.amountObserved + 1000, incident.amountLimit)),
|
||||
centsInputValue(isWarning
|
||||
? Math.max(incident.amountObserved, incident.amountLimit) + 1000
|
||||
: Math.max(incident.amountObserved + 1000, incident.amountLimit)),
|
||||
);
|
||||
const parsed = parseDollarInput(draftAmount);
|
||||
const stateLabel = incidentStateLabel(incident);
|
||||
|
||||
return (
|
||||
<Card className="overflow-hidden border-red-500/20 bg-(image:--gradient-extract-4)">
|
||||
<Card className={isWarning ? "overflow-hidden border-amber-500/30 bg-amber-500/5" : "overflow-hidden border-red-500/20 bg-(image:--gradient-extract-4)"}>
|
||||
<CardHeader className="px-5 pt-5 pb-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-red-700/90 dark:text-red-200/80">
|
||||
{incident.scopeType} hard stop
|
||||
<div className={isWarning
|
||||
? "text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-amber-700 dark:text-amber-200"
|
||||
: "text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-red-700/90 dark:text-red-200/80"}>
|
||||
{incident.scopeType} {isWarning ? "budget warning" : "hard stop"}
|
||||
</div>
|
||||
<Badge variant={incident.status === "resolved" ? "outline" : "secondary"}>
|
||||
{stateLabel}
|
||||
</Badge>
|
||||
</div>
|
||||
<CardTitle className="mt-1 text-base text-red-950 dark:text-red-50">{incident.scopeName}</CardTitle>
|
||||
<CardDescription className="mt-1 text-red-900/75 dark:text-red-100/70">
|
||||
<CardTitle className={isWarning ? "mt-1 text-base" : "mt-1 text-base text-red-950 dark:text-red-50"}>{incident.scopeName}</CardTitle>
|
||||
<CardDescription className={isWarning ? "mt-1" : "mt-1 text-red-900/75 dark:text-red-100/70"}>
|
||||
{incident.thresholdType === "hard" && incident.amountObserved < incident.amountLimit
|
||||
? `Accounting is incomplete. Known spend is ${formatCents(incident.amountObserved)}; review pending or unpriced usage in the budget policy.`
|
||||
: `Spending reached ${formatCents(incident.amountObserved)} against a limit of ${formatCents(incident.amountLimit)}.`}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div className="rounded-full border border-red-400/30 bg-red-500/10 p-2 text-red-600 dark:text-red-200">
|
||||
<AlertOctagon className="h-4 w-4" />
|
||||
</div>
|
||||
{isWarning ? (
|
||||
<div className="rounded-full border border-amber-500/30 bg-amber-500/10 p-2 text-amber-600 dark:text-amber-200">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-full border border-red-400/30 bg-red-500/10 p-2 text-red-600 dark:text-red-200">
|
||||
<AlertOctagon className="h-4 w-4" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 px-5 pb-5 pt-0">
|
||||
<div className="flex items-start gap-2 rounded-xl border border-red-400/20 bg-red-500/10 px-3 py-2 text-sm text-red-950/90 dark:text-red-50/90">
|
||||
<PauseCircle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div>
|
||||
{incident.scopeType === "project"
|
||||
? "Project execution is paused. New work in this project will not start until you resolve the budget incident."
|
||||
: "This scope is paused. New heartbeats will not start until you resolve the budget incident."}
|
||||
{isWarning ? (
|
||||
<div className="flex items-start gap-2 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-950/90 dark:text-amber-50/90">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div>
|
||||
Spending crossed the warning threshold. This warning does not pause work.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-start gap-2 rounded-xl border border-red-400/20 bg-red-500/10 px-3 py-2 text-sm text-red-950/90 dark:text-red-50/90">
|
||||
<PauseCircle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div>
|
||||
{incident.scopeType === "project"
|
||||
? "Project execution is paused. New work in this project will not start until you resolve the budget incident."
|
||||
: "This scope is paused. New heartbeats will not start until you resolve the budget incident."}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-xl border border-border/60 bg-background/60 p-3">
|
||||
<label className="text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-muted-foreground">
|
||||
@@ -96,7 +116,7 @@ export function BudgetIncidentCard({
|
||||
}}
|
||||
>
|
||||
<ArrowUpRight className="h-4 w-4" />
|
||||
{isMutating ? "Applying..." : "Raise budget & resume"}
|
||||
{isMutating ? "Applying..." : isWarning ? "Raise budget" : "Raise budget & resume"}
|
||||
</Button>
|
||||
</div>
|
||||
{parsed !== null && parsed <= incident.amountObserved ? (
|
||||
@@ -108,7 +128,7 @@ export function BudgetIncidentCard({
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button variant="ghost" className="text-muted-foreground" disabled={isMutating} onClick={onKeepPaused}>
|
||||
Keep paused
|
||||
{isWarning ? "Dismiss warning" : "Keep paused"}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
@@ -44,7 +44,14 @@ vi.mock("./MarkdownEditor", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("./InlineEntitySelector", () => ({
|
||||
InlineEntitySelector: () => null,
|
||||
InlineEntitySelector: ({ value, onChange }: { value: string; onChange: (value: string) => void }) => (
|
||||
<select aria-label="Test recipient" value={value} onChange={(event) => onChange(event.target.value)}>
|
||||
<option value="agent:first">First agent</option>
|
||||
<option value="agent:latest">Latest agent</option>
|
||||
<option value="user:me">Me</option>
|
||||
<option value="">No responsible</option>
|
||||
</select>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("./ApprovalCard", () => ({
|
||||
@@ -78,6 +85,34 @@ describe("CommentThread", () => {
|
||||
let writeTextMock: ReturnType<typeof vi.fn<(text: string) => Promise<void>>>;
|
||||
let execCommandMock: ReturnType<typeof vi.fn<typeof document.execCommand>>;
|
||||
|
||||
it("updates automatic suggestions but preserves manual choices until the task changes", () => {
|
||||
const root = createRoot(container);
|
||||
const render = (suggestion: string, draftKey = "task-one") => act(() => root.render(
|
||||
<MemoryRouter>
|
||||
<CommentThread comments={[]} onAdd={async () => {}} enableReassign
|
||||
reassignOptions={[{ id: "agent:first", label: "First agent" }]}
|
||||
currentAssigneeValue="user:me" suggestedAssigneeValue={suggestion} draftKey={draftKey} />
|
||||
</MemoryRouter>,
|
||||
));
|
||||
const selector = () => container.querySelector('select[aria-label="Test recipient"]') as HTMLSelectElement;
|
||||
render("agent:first");
|
||||
expect(selector().value).toBe("agent:first");
|
||||
render("agent:latest");
|
||||
expect(selector().value).toBe("agent:latest");
|
||||
for (const manual of ["user:me", ""]) {
|
||||
act(() => {
|
||||
selector().value = manual;
|
||||
selector().dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
render("agent:first");
|
||||
render("agent:latest");
|
||||
expect(selector().value).toBe(manual);
|
||||
}
|
||||
render("agent:first", "task-two");
|
||||
expect(selector().value).toBe("agent:first");
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
|
||||
@@ -752,6 +752,12 @@ export function CommentThread({
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [attaching, setAttaching] = useState(false);
|
||||
const effectiveSuggestedAssigneeValue = suggestedAssigneeValue ?? currentAssigneeValue;
|
||||
const manualAssigneeRef = useRef(false);
|
||||
const assigneeDraftKeyRef = useRef(draftKey);
|
||||
const selectAssignee = (value: string) => {
|
||||
manualAssigneeRef.current = true;
|
||||
setReassignTarget(value);
|
||||
};
|
||||
const [reassignTarget, setReassignTarget] = useState(effectiveSuggestedAssigneeValue);
|
||||
const [highlightCommentId, setHighlightCommentId] = useState<string | null>(null);
|
||||
const [votingTargetId, setVotingTargetId] = useState<string | null>(null);
|
||||
@@ -852,8 +858,12 @@ export function CommentThread({
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setReassignTarget(effectiveSuggestedAssigneeValue);
|
||||
}, [effectiveSuggestedAssigneeValue]);
|
||||
if (assigneeDraftKeyRef.current !== draftKey) {
|
||||
assigneeDraftKeyRef.current = draftKey;
|
||||
manualAssigneeRef.current = false;
|
||||
}
|
||||
if (!manualAssigneeRef.current) setReassignTarget(effectiveSuggestedAssigneeValue);
|
||||
}, [draftKey, effectiveSuggestedAssigneeValue]);
|
||||
|
||||
// Scroll to comment when URL hash matches #comment-{id}
|
||||
useEffect(() => {
|
||||
@@ -898,6 +908,7 @@ export function CommentThread({
|
||||
try {
|
||||
await onAdd(submittedBody, reopen, reassignment ?? undefined);
|
||||
if (draftKey) clearDraft(draftKey);
|
||||
manualAssigneeRef.current = false;
|
||||
setReassignTarget(effectiveSuggestedAssigneeValue);
|
||||
} catch {
|
||||
setBody((current) =>
|
||||
@@ -1051,7 +1062,7 @@ export function CommentThread({
|
||||
noneLabel="No responsible"
|
||||
searchPlaceholder="Search responsible..."
|
||||
emptyMessage="No responsible found."
|
||||
onChange={setReassignTarget}
|
||||
onChange={selectAssignee}
|
||||
className="text-xs h-8"
|
||||
renderTriggerValue={(option) => {
|
||||
if (!option) return <span className="text-muted-foreground">Responsible</span>;
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
Download,
|
||||
FlaskConical,
|
||||
KeyRound,
|
||||
Link2,
|
||||
MailPlus,
|
||||
MonitorCog,
|
||||
Puzzle,
|
||||
@@ -27,6 +28,7 @@ import { useCompany } from "@/context/CompanyContext";
|
||||
import { useSidebar } from "@/context/SidebarContext";
|
||||
import { useCloudInstance } from "@/hooks/useCloudInstance";
|
||||
import { useHiddenSettings } from "@/hooks/useHiddenSettings";
|
||||
import { useFastResponsesEnabled } from "@/hooks/useFastResponsesEnabled";
|
||||
import { usePluginSlots } from "@/plugins/slots";
|
||||
import { SidebarNavItem } from "./SidebarNavItem.production";
|
||||
|
||||
@@ -46,6 +48,7 @@ export function CompanySettingsSidebar() {
|
||||
const { selectedCompany, selectedCompanyId } = useCompany();
|
||||
const { isMobile, setSidebarOpen } = useSidebar();
|
||||
const { hidden: hiddenSettings } = useHiddenSettings();
|
||||
const { enabled: fastResponsesEnabled } = useFastResponsesEnabled();
|
||||
const showPage = (pageKey: string) => !hiddenSettings.has(pageKey);
|
||||
const showPlugins = showPage("instance.plugins");
|
||||
// Import is floored server-side on cloud-managed instances (403 cloud_managed), so the
|
||||
@@ -143,6 +146,9 @@ export function CompanySettingsSidebar() {
|
||||
end
|
||||
/>
|
||||
)}
|
||||
{fastResponsesEnabled && (
|
||||
<SidebarNavItem to="/company/settings/connections" label="Connections" icon={Link2} end />
|
||||
)}
|
||||
{showPage("instance.access") && (
|
||||
<SidebarNavItem
|
||||
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/access`}
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
Download,
|
||||
FlaskConical,
|
||||
KeyRound,
|
||||
Link2,
|
||||
MonitorCog,
|
||||
Puzzle,
|
||||
Shield,
|
||||
@@ -24,6 +25,7 @@ import { queryKeys } from "@/lib/queryKeys";
|
||||
import { useCompany } from "@/context/CompanyContext";
|
||||
import { useCloudInstance } from "@/hooks/useCloudInstance";
|
||||
import { useHiddenSettings } from "@/hooks/useHiddenSettings";
|
||||
import { useFastResponsesEnabled } from "@/hooks/useFastResponsesEnabled";
|
||||
import { usePluginSlots } from "@/plugins/slots";
|
||||
import { SidebarNavItem } from "./SidebarNavItem";
|
||||
import { ContextualSidebarFrame } from "./ContextualSidebarFrame";
|
||||
@@ -44,6 +46,7 @@ function isSandboxProviderOnly(plugin: PluginRecord): boolean {
|
||||
export function CompanySettingsSidebar() {
|
||||
const { selectedCompanyId } = useCompany();
|
||||
const { hidden: hiddenSettings } = useHiddenSettings();
|
||||
const { enabled: fastResponsesEnabled } = useFastResponsesEnabled();
|
||||
const showPage = (pageKey: string) => !hiddenSettings.has(pageKey);
|
||||
const showPlugins = showPage("instance.plugins");
|
||||
// Import is floored server-side on cloud-managed instances (403 cloud_managed), so the
|
||||
@@ -142,6 +145,9 @@ export function CompanySettingsSidebar() {
|
||||
end
|
||||
/>
|
||||
)}
|
||||
{fastResponsesEnabled && (
|
||||
<SidebarNavItem to="/company/settings/connections" label="Connections" icon={Link2} end />
|
||||
)}
|
||||
{showPage("instance.access") && (
|
||||
<SidebarNavItem
|
||||
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/access`}
|
||||
|
||||
@@ -2,15 +2,18 @@ import type { ReactNode } from "react";
|
||||
import type { CostByAgent } from "@paperclipai/shared";
|
||||
import { formatCents } from "../lib/utils";
|
||||
import { CostEstimateLabel } from "./CostEstimateLabel";
|
||||
import { Badge } from "./ui/badge";
|
||||
|
||||
export function CostAmount({
|
||||
costCents,
|
||||
eventCount,
|
||||
estimatedEventCount,
|
||||
unpricedEventCount,
|
||||
showUnavailableCount = false,
|
||||
suffix,
|
||||
}: Pick<CostByAgent, "costCents"> & Partial<Pick<CostByAgent, "eventCount" | "estimatedEventCount">> & {
|
||||
unpricedEventCount?: number;
|
||||
showUnavailableCount?: boolean;
|
||||
suffix?: ReactNode;
|
||||
}) {
|
||||
const entirelyUnpriced = costCents === 0 && (eventCount ?? 0) > 0 && unpricedEventCount === eventCount;
|
||||
@@ -21,6 +24,9 @@ export function CostAmount({
|
||||
{suffix}
|
||||
</div>
|
||||
<CostEstimateLabel eventCount={eventCount} estimatedEventCount={estimatedEventCount} />
|
||||
{showUnavailableCount && !!unpricedEventCount && <Badge variant="outline" className="font-normal text-muted-foreground">
|
||||
{unpricedEventCount} {unpricedEventCount === 1 ? "cost" : "costs"} unavailable
|
||||
</Badge>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { appearanceForPalette, agentAvatarUrl, type CostDataQualityItem, type CostDataQualityReason, type CostDataQualityReport } from "@paperclipai/shared";
|
||||
import { ToastProvider, useToastState } from "../context/ToastContext";
|
||||
import { CostDataQualityNotice } from "./CostDataQualityNotice";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ dataQuality: vi.fn(), retryAccounting: vi.fn() }));
|
||||
vi.mock("../api/costs", () => ({ costsApi: mocks }));
|
||||
vi.mock("../context/CompanyContext", () => ({ useCompany: () => ({ selectedCompany: { issuePrefix: "PAP" } }) }));
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const key = ["costs", "company", "2026-10-01", "2026-10-09"];
|
||||
function item(reason: CostDataQualityReason): CostDataQualityItem {
|
||||
return { id: reason, runId: `${reason}-run`, agentId: "codie", agentName: "Codie", occurredAt: "2026-10-09T12:00:00Z", provider: "openai", model: "gpt-6-astra", reason };
|
||||
}
|
||||
function report(canRetry = true): CostDataQualityReport {
|
||||
return { canRetry, events: [item("unknown_billing"), item("missing_model"), item("missing_price")],
|
||||
runs: [item("waiting_for_receipt"), item("receipt_unavailable"), item("retryable")], hasMoreEvents: false, hasMoreRuns: false };
|
||||
}
|
||||
function ToastStatus() {
|
||||
const toasts = useToastState();
|
||||
return <div aria-label="Notifications">{toasts.map(toast => <p role="status" key={toast.id}>{toast.title} {toast.body}</p>)}</div>;
|
||||
}
|
||||
describe("actionable cost notices", () => {
|
||||
let container: HTMLDivElement, root: ReturnType<typeof createRoot>, client: QueryClient;
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks(); mocks.dataQuality.mockResolvedValue(report()); mocks.retryAccounting.mockResolvedValue({ accounted: true });
|
||||
container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
||||
});
|
||||
afterEach(() => { act(() => root.unmount()); client.clear(); container.remove(); });
|
||||
async function render(counts: { unpricedCount?: number; pendingCount?: number; unknownBillingCount?: number } = {}) {
|
||||
await act(async () => root.render(<MemoryRouter initialEntries={["/PAP/activity/costs"]}><QueryClientProvider client={client}><ToastProvider><ToastStatus />
|
||||
<CostDataQualityNotice companyId="company" from="2026-10-01" to="2026-10-09" reportKey={key} unpricedCount={12} pendingCount={4} unknownBillingCount={9} {...counts} />
|
||||
</ToastProvider></QueryClientProvider></MemoryRouter>));
|
||||
}
|
||||
function button(text: string) { return [...container.querySelectorAll("button")].find(button => button.textContent === text)!; }
|
||||
async function click(text: string) { await act(async () => button(text).click()); }
|
||||
async function loaded() { await act(async () => vi.waitFor(() => expect(container.textContent).toContain("Ready to record"))); }
|
||||
|
||||
it("loads bounded details only on demand using the displayed period", async () => {
|
||||
await render(); expect(mocks.dataQuality).not.toHaveBeenCalled();
|
||||
expect(button("16 run costs unavailable").getAttribute("aria-expanded")).toBe("false");
|
||||
expect(container.textContent).toBe("16 run costs unavailable");
|
||||
expect(container.querySelector('svg[aria-hidden="true"]')).not.toBeNull();
|
||||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||||
await click("16 run costs unavailable"); await loaded();
|
||||
expect(mocks.dataQuality).toHaveBeenCalledExactlyOnceWith("company", "2026-10-01", "2026-10-09");
|
||||
expect(button("16 run costs unavailable").getAttribute("aria-expanded")).toBe("true");
|
||||
const details = document.getElementById(button("16 run costs unavailable").getAttribute("aria-controls")!)!;
|
||||
expect(details.textContent).not.toContain("Totals include known charges only.");
|
||||
expect(details.textContent).not.toContain("12 entries without prices · 4 runs without final cost data · 9 entries with unknown billing");
|
||||
expect(details.textContent).not.toContain("Includes 12 estimated charges.");
|
||||
await click("16 run costs unavailable");
|
||||
expect(container.querySelector("ul")).toBeNull();
|
||||
expect(container.textContent).toBe("16 run costs unavailable");
|
||||
});
|
||||
|
||||
it("explains future configuration fixes and links to the affected runs in the active company", async () => {
|
||||
await render(); await click("16 run costs unavailable"); await loaded();
|
||||
const row = (label: string) => [...container.querySelectorAll('[data-slot="badge"]')].find(badge => badge.textContent === label)!.closest("li")!;
|
||||
const billing = row("Billing category unknown");
|
||||
expect(billing.textContent).toContain("Any recorded charges are included in the inference ledger.");
|
||||
const configuration = container.querySelector('a[href="/PAP/agents/codie/configuration"]')!;
|
||||
expect(configuration.textContent).toBe("Codie");
|
||||
expect(configuration.closest("h3")!.textContent).toBe("Codie");
|
||||
expect(container.querySelectorAll('a[href="/PAP/agents/codie/configuration"]')).toHaveLength(1);
|
||||
expect(billing.querySelector('a[href="/PAP/agents/codie/configuration"]')).toBeNull();
|
||||
expect(billing.querySelector('a[href="/PAP/agents/codie/runs/unknown_billing-run"]')).not.toBeNull();
|
||||
for (const link of container.querySelectorAll("a")) expect(link.hasAttribute("data-slot")).toBe(false);
|
||||
expect(container.querySelectorAll("h3")).toHaveLength(1);
|
||||
expect(container.querySelectorAll('[data-slot="agent-avatar"]')).toHaveLength(1);
|
||||
expect(container.textContent).toContain("Changing settings will not reprice this past run.");
|
||||
const runs = [row("Receiving usage"), row("Final usage unavailable")];
|
||||
expect(runs[0].textContent).toContain("You do not need to rerun the agent.");
|
||||
expect(runs[1].textContent).toContain("Its cost remains unresolved for budget checks.");
|
||||
expect(runs[1].textContent).toContain("rerunning the agent will not recover this usage.");
|
||||
expect(runs[0].querySelector("button")).toBeNull();
|
||||
expect(runs[1].querySelector("button")).toBeNull();
|
||||
expect([...container.querySelectorAll("button")].filter(row => row.textContent === "Retry cost recording")).toHaveLength(1);
|
||||
const actionLine = button("Retry cost recording").parentElement!;
|
||||
expect(actionLine.children[0].tagName).toBe("TIME");
|
||||
expect(actionLine.children[1].textContent).toBe("View run");
|
||||
expect(actionLine.children[2].textContent).toBe("Retry cost recording");
|
||||
expect(button("Retry cost recording").getAttribute("data-variant")).toBe("link");
|
||||
});
|
||||
|
||||
it("groups all kinds of cost gaps by agent identity, alphabetizes names, and preserves appearances and newest-first entries", async () => {
|
||||
const appearance = appearanceForPalette("deep-tide");
|
||||
mocks.dataQuality.mockResolvedValue({ canRetry: true, hasMoreEvents: false, hasMoreRuns: false,
|
||||
events: [
|
||||
{ ...item("missing_model"), agentId: "fry", agentName: "fry" },
|
||||
{ ...item("missing_price"), id: "shared-id", agentAppearance: appearance, occurredAt: "2026-10-08T12:00:00Z" },
|
||||
{ ...item("unknown_billing"), agentId: null, agentName: null, runId: null },
|
||||
{ ...item("missing_price"), id: "other-codie", agentId: "codie-2" },
|
||||
],
|
||||
runs: [
|
||||
{ ...item("receipt_unavailable"), agentId: "leela", agentName: "Leela" },
|
||||
{ ...item("retryable"), id: "shared-id", agentAppearance: appearance },
|
||||
],
|
||||
});
|
||||
await render(); await click("16 run costs unavailable"); await loaded();
|
||||
const groups = [...container.querySelectorAll('[aria-label="Cost details by agent"] > li')];
|
||||
expect(groups.map(group => group.querySelector("h3")!.textContent)).toEqual(["Codie", "Codie", "fry", "Leela", "Paperclip services"]);
|
||||
const codieItems = groups[0].querySelectorAll("li");
|
||||
expect(codieItems).toHaveLength(2);
|
||||
expect(codieItems[0].textContent).toContain("Ready to record");
|
||||
expect(codieItems[1].textContent).toContain("Cost unavailable");
|
||||
expect(groups[1].querySelectorAll("li")).toHaveLength(1);
|
||||
expect(groups[0].querySelector("img")?.getAttribute("src")).toBe(agentAvatarUrl(appearance, 20));
|
||||
expect(groups[4].querySelector("a")).toBeNull();
|
||||
});
|
||||
|
||||
it("does not label priced unknown billing or estimates as unavailable costs", async () => {
|
||||
await render({ unpricedCount: 0, pendingCount: 0, unknownBillingCount: 1 });
|
||||
expect(container.textContent).toBe("1 billing type unknown");
|
||||
await click("1 billing type unknown"); await loaded();
|
||||
expect(container.textContent).toContain("Billing category unknown");
|
||||
expect(container.textContent).not.toContain("Totals include known charges only.");
|
||||
expect(container.textContent).not.toContain("Includes 12 estimated charges.");
|
||||
});
|
||||
|
||||
it("records saved costs without rerunning work and refreshes every period for this company", async () => {
|
||||
let finish!: (result: { accounted: boolean }) => void;
|
||||
mocks.retryAccounting.mockImplementation(() => new Promise(resolve => { finish = resolve; }));
|
||||
await render(); await click("16 run costs unavailable"); await loaded();
|
||||
const invalidate = vi.spyOn(client, "invalidateQueries");
|
||||
await click("Retry cost recording");
|
||||
await act(async () => vi.waitFor(() => expect(button("Retry cost recording").disabled).toBe(true)));
|
||||
await click("Retry cost recording");
|
||||
expect(mocks.retryAccounting).toHaveBeenCalledTimes(1);
|
||||
await act(async () => finish({ accounted: true }));
|
||||
await act(async () => vi.waitFor(() => expect(container.textContent).toContain("Costs recorded.")));
|
||||
expect(mocks.retryAccounting).toHaveBeenCalledExactlyOnceWith("company", "retryable-run");
|
||||
expect(invalidate).toHaveBeenCalledWith({ queryKey: ["costs", "company"] });
|
||||
expect(invalidate).toHaveBeenCalledWith({ queryKey: ["cost-subscriptions", "company"] });
|
||||
});
|
||||
|
||||
it("keeps retry confirmation after the refreshed report removes the run and the notice unmounts", async () => {
|
||||
mocks.dataQuality.mockResolvedValueOnce({ ...report(), events: [], runs: [item("retryable")] })
|
||||
.mockResolvedValue({ ...report(), events: [], runs: [] });
|
||||
await render({ unpricedCount: 0, pendingCount: 1, unknownBillingCount: 0 });
|
||||
await click("1 run cost unavailable"); await loaded();
|
||||
await click("Retry cost recording");
|
||||
await act(async () => vi.waitFor(() => expect(container.textContent).toContain("No cost gaps remain")));
|
||||
expect(container.textContent).not.toContain("Retry cost recording");
|
||||
await act(async () => root.render(<MemoryRouter><QueryClientProvider client={client}>
|
||||
<ToastProvider><ToastStatus /></ToastProvider>
|
||||
</QueryClientProvider></MemoryRouter>));
|
||||
expect(container.textContent).toContain("Costs recorded. The agent was not rerun.");
|
||||
});
|
||||
|
||||
it("makes stale retry results understandable and never renders raw provider errors", async () => {
|
||||
mocks.retryAccounting.mockResolvedValueOnce({ accounted: false }).mockRejectedValueOnce(new Error("SECRET sh -c provider --token credential"));
|
||||
await render(); await click("16 run costs unavailable"); await loaded();
|
||||
await click("Retry cost recording");
|
||||
await act(async () => vi.waitFor(() => expect(container.textContent).toContain("No new cost data is available. The agent was not rerun.")));
|
||||
await click("Retry cost recording");
|
||||
await act(async () => vi.waitFor(() => expect(container.textContent).toContain("Cost recording failed. Try again shortly.")));
|
||||
expect(container.textContent).not.toContain("SECRET");
|
||||
expect(container.textContent).not.toContain("credential");
|
||||
});
|
||||
|
||||
it("keeps viewer details readable without exposing the retry action", async () => {
|
||||
mocks.dataQuality.mockResolvedValue(report(false));
|
||||
await render(); await click("16 run costs unavailable"); await loaded();
|
||||
expect(container.textContent).not.toContain("Retry cost recording");
|
||||
expect(mocks.retryAccounting).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retains the last successful details through a failed background refresh", async () => {
|
||||
await render(); await click("16 run costs unavailable"); await loaded();
|
||||
mocks.dataQuality.mockRejectedValue(new Error("SECRET backend exception"));
|
||||
await act(async () => { await client.invalidateQueries({ queryKey: [...key, "data-quality"] }); });
|
||||
await act(async () => vi.waitFor(() => expect(container.textContent).toContain("Showing the last loaded cost details.")));
|
||||
expect(container.textContent).toContain("Ready to record");
|
||||
expect(container.textContent).not.toContain("SECRET");
|
||||
});
|
||||
|
||||
it("offers a safe first-load retry and explains truncated results", async () => {
|
||||
mocks.dataQuality.mockRejectedValueOnce(new Error("SECRET command"));
|
||||
await render(); await click("16 run costs unavailable");
|
||||
await act(async () => vi.waitFor(() => expect(container.textContent).toContain("Cost details could not be loaded.")));
|
||||
expect(container.textContent).not.toContain("SECRET");
|
||||
mocks.dataQuality.mockResolvedValue({ ...report(), hasMoreRuns: true });
|
||||
await click("Retry loading"); await loaded();
|
||||
expect(container.textContent).toContain("Select a shorter date range to inspect more.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import { useId, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { ChevronDown, ChevronRight } from "lucide-react";
|
||||
import { Link } from "../lib/router";
|
||||
import type { CostDataQualityItem, CostDataQualityReason } from "@paperclipai/shared";
|
||||
import { costsApi } from "../api/costs";
|
||||
import { formatDateTime } from "../lib/utils";
|
||||
import { Button } from "./ui/button";
|
||||
import { Badge } from "./ui/badge";
|
||||
import { AgentAvatar } from "./AgentAvatar";
|
||||
import { useToastActions } from "../context/ToastContext";
|
||||
|
||||
const explanations: Record<CostDataQualityReason, { label: string; description: string }> = {
|
||||
unknown_billing: {
|
||||
label: "Billing category unknown",
|
||||
description: "This run did not identify API or subscription billing. Any recorded charges are included in the inference ledger. For future runs, select an AI connection in the agent’s configuration so Paperclip can identify its billing.",
|
||||
},
|
||||
missing_model: {
|
||||
label: "Model not reported",
|
||||
description: "Token usage was recorded without a model, so Paperclip cannot estimate its cost. Select an explicit model in the agent’s configuration for future runs. Changing settings will not reprice this past run.",
|
||||
},
|
||||
missing_price: {
|
||||
label: "Cost unavailable",
|
||||
description: "The provider did not supply a reliable price for this usage. There is no action required for this past entry. New API runs with complete usage and a supported model are estimated automatically.",
|
||||
},
|
||||
waiting_for_receipt: {
|
||||
label: "Receiving usage",
|
||||
description: "This run has stopped. Paperclip is waiting for its final usage data and will record it automatically. You do not need to rerun the agent.",
|
||||
},
|
||||
receipt_unavailable: {
|
||||
label: "Final usage unavailable",
|
||||
description: "This run stopped without final usage data. Its cost remains unresolved for budget checks. Paperclip will record a late receipt if one arrives; rerunning the agent will not recover this usage.",
|
||||
},
|
||||
retryable: {
|
||||
label: "Ready to record",
|
||||
description: "Saved usage data is ready to be recorded. Paperclip retries automatically, or you can retry now. This records costs only; it does not rerun the agent.",
|
||||
},
|
||||
};
|
||||
|
||||
export function CostDataQualityNotice({ companyId, from, to, reportKey, unpricedCount, pendingCount, unknownBillingCount }: {
|
||||
companyId: string; from?: string; to?: string; reportKey: readonly unknown[];
|
||||
unpricedCount: number; pendingCount: number; unknownBillingCount: number;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const unavailableCount = unpricedCount + pendingCount;
|
||||
const hasCostGaps = unavailableCount > 0 || unknownBillingCount > 0;
|
||||
const detailsId = useId();
|
||||
const client = useQueryClient();
|
||||
const { pushToast } = useToastActions();
|
||||
const key = [...reportKey, "data-quality"];
|
||||
const { data, error, isPending, refetch } = useQuery({
|
||||
queryKey: key,
|
||||
queryFn: () => costsApi.dataQuality(companyId, from, to),
|
||||
enabled: open && hasCostGaps,
|
||||
refetchInterval: open && hasCostGaps ? 30_000 : false,
|
||||
});
|
||||
const retry = useMutation({
|
||||
mutationFn: (runId: string) => costsApi.retryAccounting(companyId, runId),
|
||||
onSuccess: result => {
|
||||
pushToast({
|
||||
title: result.accounted ? "Costs recorded." : "No new cost data is available.",
|
||||
body: "The agent was not rerun.",
|
||||
tone: result.accounted ? "success" : "info",
|
||||
});
|
||||
client.invalidateQueries({ queryKey: ["costs", companyId] });
|
||||
client.invalidateQueries({ queryKey: key });
|
||||
client.invalidateQueries({ queryKey: ["cost-subscriptions", companyId] });
|
||||
},
|
||||
});
|
||||
const label = unavailableCount > 0
|
||||
? `${unavailableCount} run ${unavailableCount === 1 ? "cost" : "costs"} unavailable`
|
||||
: `${unknownBillingCount} billing ${unknownBillingCount === 1 ? "type" : "types"} unknown`;
|
||||
|
||||
const groups = new Map<string | null, {
|
||||
agent: { id?: string; name: string; appearance?: CostDataQualityItem["agentAppearance"] };
|
||||
items: { item: CostDataQualityItem; source: "event" | "run" }[];
|
||||
}>();
|
||||
for (const [source, items] of [["event", data?.events ?? []], ["run", data?.runs ?? []]] as const) {
|
||||
for (const item of items) {
|
||||
let group = groups.get(item.agentId);
|
||||
if (!group) {
|
||||
group = { agent: { id: item.agentId ?? undefined, name: item.agentName ?? (item.agentId ? "Unknown agent" : "Paperclip services"), appearance: item.agentAppearance }, items: [] };
|
||||
groups.set(item.agentId, group);
|
||||
}
|
||||
group.items.push({ item, source });
|
||||
}
|
||||
}
|
||||
const sortedGroups = [...groups.values()].sort((a, b) =>
|
||||
a.agent.name.localeCompare(b.agent.name, "en", { sensitivity: "base", numeric: true })
|
||||
|| (a.agent.id ?? "").localeCompare(b.agent.id ?? ""));
|
||||
for (const group of sortedGroups) group.items.sort((a, b) =>
|
||||
Date.parse(b.item.occurredAt) - Date.parse(a.item.occurredAt)
|
||||
|| `${a.source}:${a.item.id}`.localeCompare(`${b.source}:${b.item.id}`));
|
||||
|
||||
function itemRow(item: CostDataQualityItem, source: "event" | "run") {
|
||||
const explanation = explanations[item.reason];
|
||||
return <li key={`${source}:${item.id}`} className="space-y-2 border-b border-border py-3 last:border-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="outline" className="font-normal text-muted-foreground">{explanation.label}</Badge>
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs">
|
||||
<time dateTime={item.occurredAt}>{formatDateTime(item.occurredAt)}</time>
|
||||
{item.runId && item.agentId && <Link className="text-primary underline underline-offset-4 hover:text-primary/80" to={`/agents/${item.agentId}/runs/${item.runId}`}>View run</Link>}
|
||||
{item.reason === "retryable" && item.runId && data?.canRetry && <Button type="button" variant="link" size="sm" className="h-auto p-0 text-xs font-normal underline hover:text-primary/80" disabled={retry.isPending}
|
||||
onClick={() => { retry.reset(); retry.mutate(item.runId!); }}>Retry cost recording</Button>}
|
||||
</div>
|
||||
</div>
|
||||
<p>{explanation.description}</p>
|
||||
{retry.variables === item.runId && retry.isPending && <p role="status">Recording saved costs…</p>}
|
||||
{retry.variables === item.runId && retry.error && <p role="status">Cost recording failed. Try again shortly.</p>}
|
||||
</li>;
|
||||
}
|
||||
|
||||
return <div className="space-y-2 text-sm text-muted-foreground">
|
||||
<Button type="button" variant="ghost" size="sm" className="h-auto justify-start gap-1 px-0 py-1 font-normal has-[>svg]:px-0" aria-expanded={open} aria-controls={detailsId} onClick={() => setOpen(value => !value)}>
|
||||
{open ? <ChevronDown className="size-3" aria-hidden="true" /> : <ChevronRight className="size-3" aria-hidden="true" />}
|
||||
{label}
|
||||
</Button>
|
||||
{open && <div id={detailsId} className="space-y-2">
|
||||
{hasCostGaps && isPending && <p role="status">Loading affected runs…</p>}
|
||||
{hasCostGaps && error && !data && <div className="flex flex-wrap items-center gap-2"><p role="status">Cost details could not be loaded.</p><Button variant="outline" size="sm" onClick={() => refetch()}>Retry loading</Button></div>}
|
||||
{hasCostGaps && data && <>
|
||||
{error && <p role="status">Showing the last loaded cost details. Updates will resume automatically.</p>}
|
||||
{data.events.length === 0 && data.runs.length === 0 && <p role="status">No cost gaps remain in this period.</p>}
|
||||
<ul aria-label="Cost details by agent" className="space-y-4">
|
||||
{sortedGroups.map(group => <li key={group.agent.id ?? "services"}>
|
||||
<h3 className="flex items-center gap-2 font-medium text-foreground">
|
||||
<AgentAvatar agent={group.agent} size={20} />
|
||||
{group.agent.id ? <Link className="text-primary underline underline-offset-4 hover:text-primary/80" to={`/agents/${group.agent.id}/configuration`}>{group.agent.name}</Link> : group.agent.name}
|
||||
</h3>
|
||||
<ul aria-label={`${group.agent.name} cost details`}>{group.items.map(({ item, source }) => itemRow(item, source))}</ul>
|
||||
</li>)}
|
||||
</ul>
|
||||
{(data.hasMoreEvents || data.hasMoreRuns) && <p className="text-xs">Showing the 25 most recent entries in each category. Select a shorter date range to inspect more.</p>}
|
||||
</>}
|
||||
</div>}
|
||||
</div>;
|
||||
}
|
||||
@@ -42,7 +42,9 @@ export function EmailMessageCard({
|
||||
message,
|
||||
publication,
|
||||
issueId,
|
||||
contextNotice = false,
|
||||
}: {
|
||||
contextNotice?: boolean;
|
||||
message: EmailMessage;
|
||||
publication?: EmailPublicationSummary;
|
||||
issueId: string;
|
||||
@@ -57,7 +59,7 @@ export function EmailMessageCard({
|
||||
aria-label={
|
||||
message.direction === "inbound" ? "Email received" : "Email sent"
|
||||
}
|
||||
className="space-y-4 rounded-xl border border-border bg-card p-5"
|
||||
className={contextNotice ? "task-context-notice space-y-3" : "space-y-4 rounded-xl border border-border bg-card p-5"}
|
||||
>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<span className="flex items-center gap-2 text-sm font-semibold">
|
||||
|
||||
@@ -36,6 +36,7 @@ export function EmailTaskActivity({
|
||||
)}
|
||||
{messages.map((m) => (
|
||||
<EmailMessageCard
|
||||
contextNotice
|
||||
key={m.id}
|
||||
issueId={issueId}
|
||||
message={m}
|
||||
@@ -78,7 +79,7 @@ function EmailDelivery({
|
||||
{p.request && !p.providerMessageId && (
|
||||
<article
|
||||
aria-label="Email send intent"
|
||||
className="space-y-3 rounded-lg border border-border p-4"
|
||||
className="task-context-notice space-y-3"
|
||||
>
|
||||
<p className="font-semibold">{p.request.subject ?? "Email reply"}</p>
|
||||
{p.request.to && <p>To: {p.request.to.join(", ")}</p>}
|
||||
|
||||
@@ -36,8 +36,7 @@ describe("stopped task recovery notice", () => {
|
||||
const notice = container.querySelector('[role="status"][aria-label="Task recovery"]')!;
|
||||
expect(notice.textContent).toContain("Recorded work is preserved");
|
||||
expect(notice.textContent).toContain("Retry");
|
||||
expect(notice.classList.contains("border")).toBe(true);
|
||||
expect(notice.classList.contains("bg-muted")).toBe(true);
|
||||
expect(notice.classList.contains("task-context-notice")).toBe(true);
|
||||
expect(notice.querySelector("a")?.getAttribute("href")).toBe("/agents/agent/runs/failed-run");
|
||||
});
|
||||
it.each([false, true])("explains cancelled runs and saved input; continue eligibility %s", async canContinue => {
|
||||
@@ -107,7 +106,12 @@ describe("stopped task recovery notice", () => {
|
||||
nextAction: "The original sandbox is retained. Recover the missing files and record workspace repair evidence.",
|
||||
}} />
|
||||
</QueryClientProvider>));
|
||||
expect(container.textContent).toContain("Recover the missing files");
|
||||
expect(container.textContent).toContain("could not restore the agent's workspace files");
|
||||
expect(container.textContent).toContain("A board operator must recover the files");
|
||||
// The hold also covers unsafe archives and local runs, so the notice must not promise retries or a kept sandbox.
|
||||
expect(container.textContent).not.toContain("retrying");
|
||||
expect(container.textContent).not.toContain("no work is lost");
|
||||
expect(container.querySelector("details")?.textContent).toContain("Recover the missing files");
|
||||
expect(container.querySelector("button")).toBeNull();
|
||||
expect(container.querySelector("a")?.textContent).toBe("Inspect run");
|
||||
expect(agentsApi.retryFailedRun).not.toHaveBeenCalled();
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ExecutionBlocker } from "@paperclipai/shared";
|
||||
import type { ExecutionBlocker, Issue } from "@paperclipai/shared";
|
||||
import { WorkspaceFileRecovery } from "./WorkspaceFileRecovery";
|
||||
import { agentsApi } from "../api/agents";
|
||||
import { activityApi } from "../api/activity";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import { Button } from "./ui/button";
|
||||
import { cn } from "../lib/utils";
|
||||
import { Link } from "../lib/router";
|
||||
|
||||
export function ExecutionBlockerNotice({ companyId, issueId, blocker, onRetried }: {
|
||||
export function ExecutionBlockerNotice({ companyId, issueId, issueStatus, canManage = false, blocker, onRetried, className }: {
|
||||
className?: string;
|
||||
companyId: string;
|
||||
issueId: string;
|
||||
issueStatus?: Issue["status"];
|
||||
canManage?: boolean;
|
||||
blocker: ExecutionBlocker;
|
||||
onRetried: () => void;
|
||||
}) {
|
||||
@@ -33,11 +38,24 @@ export function ExecutionBlockerNotice({ companyId, issueId, blocker, onRetried
|
||||
},
|
||||
});
|
||||
return (
|
||||
<div role="status" aria-label="Task recovery" className="mx-(--sz-execution-blocker-inline) my-(--sz-execution-blocker-block) flex flex-wrap items-center justify-between execution-blocker-notice border border-border bg-muted text-foreground">
|
||||
<div role="status" aria-label="Task recovery" className={cn("task-context-notice flex flex-wrap items-center justify-between gap-2", className)}>
|
||||
<div className="min-w-0 flex-1 break-words">
|
||||
<p>{modelRejected ? "Model unavailable." : "Recovery needed."}{blocker.runError ? ` ${blocker.runError}` : ""}</p>
|
||||
{modelRejected && <p>Choose a supported model or clear the task's model override, then retry.</p>}
|
||||
<p>{blocker.nextAction}</p>
|
||||
{blocker.workspaceRepairRequired ? (
|
||||
<>
|
||||
{/* The stored next action is an operator runbook step; lead with what happened. This hold also covers
|
||||
unsafe archives and local runs, so do not claim retries or a retained sandbox here. */}
|
||||
<p>
|
||||
Paperclip could not restore the agent's workspace files after its last run. A board operator must
|
||||
recover the files before the agent can continue.
|
||||
</p>
|
||||
<details>
|
||||
<summary className="cursor-pointer">Technical details</summary>
|
||||
<p>{blocker.nextAction}</p>
|
||||
</details>
|
||||
</>
|
||||
) : <p>{blocker.nextAction}</p>}
|
||||
{Boolean(blocker.savedMessageCount) && (
|
||||
<p>{blocker.savedMessageCount} saved {blocker.savedMessageCount === 1 ? "message is" : "messages are"} waiting for recovery.</p>
|
||||
)}
|
||||
@@ -57,6 +75,8 @@ export function ExecutionBlockerNotice({ companyId, issueId, blocker, onRetried
|
||||
<p role="alert" className="w-full text-destructive">{retry.error.message}</p>
|
||||
)}
|
||||
{runsError && <p role="alert" className="w-full text-destructive">{runsError.message}</p>}
|
||||
{issueStatus && <WorkspaceFileRecovery key={`${blocker.recoveryActionId}:${blocker.runId}`} issueId={issueId}
|
||||
issueStatus={issueStatus} blocker={blocker} canManage={canManage} onRecorded={onRetried} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -59,7 +59,8 @@ export function ExternalObjectStatusIcon({
|
||||
const livenessSuffix = liveness === "fresh" || liveness === "unknown"
|
||||
? ""
|
||||
: ` (${externalObjectLivenessLabel(liveness)})`;
|
||||
const ariaLabel = `${label ?? externalObjectCategoryLabel(category)}${livenessSuffix}`;
|
||||
const baseLabel = label ?? externalObjectCategoryLabel(category);
|
||||
const ariaLabel = `${baseLabel}${baseLabel.includes(externalObjectLivenessLabel(liveness)) ? "" : livenessSuffix}`;
|
||||
|
||||
// The clock overlay needs a positioned wrapper. Inline mode keeps the icon
|
||||
// tight to the surrounding text; pill mode expects to size by sizeClassName.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2487,6 +2487,7 @@ function IssueChatAssistantMessage({
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{custom.origin === "fast_response" && <div className="max-w-xs px-2 py-2 text-xs text-muted-foreground">Platform-generated acknowledgement. The agent’s substantive response follows separately.</div>}
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
void copyTextToClipboard(copyText).catch((error) => {
|
||||
@@ -4762,6 +4763,12 @@ const IssueChatComposer = forwardRef<
|
||||
const dragDepthRef = useRef(0);
|
||||
const effectiveSuggestedAssigneeValue =
|
||||
suggestedAssigneeValue ?? currentAssigneeValue;
|
||||
const manualAssigneeRef = useRef(false);
|
||||
const assigneeDraftKeyRef = useRef(draftKey);
|
||||
const selectAssignee = (value: string) => {
|
||||
manualAssigneeRef.current = true;
|
||||
setReassignTarget(value);
|
||||
};
|
||||
const [reassignTarget, setReassignTarget] = useState(
|
||||
effectiveSuggestedAssigneeValue,
|
||||
);
|
||||
@@ -4918,8 +4925,12 @@ const IssueChatComposer = forwardRef<
|
||||
}, [draftKey]);
|
||||
|
||||
useEffect(() => {
|
||||
setReassignTarget(effectiveSuggestedAssigneeValue);
|
||||
}, [effectiveSuggestedAssigneeValue]);
|
||||
if (assigneeDraftKeyRef.current !== draftKey) {
|
||||
assigneeDraftKeyRef.current = draftKey;
|
||||
manualAssigneeRef.current = false;
|
||||
}
|
||||
if (!manualAssigneeRef.current) setReassignTarget(effectiveSuggestedAssigneeValue);
|
||||
}, [draftKey, effectiveSuggestedAssigneeValue]);
|
||||
|
||||
useEffect(() => {
|
||||
setPendingWorkMode(resolvedIssueWorkMode);
|
||||
@@ -5064,6 +5075,7 @@ const IssueChatComposer = forwardRef<
|
||||
setComposerAttachments((current) =>
|
||||
current.filter((item) => !submittedAttachmentKeys.has(item.id)),
|
||||
);
|
||||
manualAssigneeRef.current = false;
|
||||
setReassignTarget(effectiveSuggestedAssigneeValue);
|
||||
setRunSettings(null);
|
||||
} catch (error) {
|
||||
@@ -5605,7 +5617,7 @@ const IssueChatComposer = forwardRef<
|
||||
overrides={assigneeAdapterOverrides}
|
||||
settings={runSettings}
|
||||
onSettingsChange={setRunSettings}
|
||||
onAssigneeChange={setReassignTarget}
|
||||
onAssigneeChange={selectAssignee}
|
||||
triggerRef={reassignTriggerRef}
|
||||
renderAssigneeIdentity={(value) => {
|
||||
const selected = value.startsWith("agent:") ? agentMap.get(value.slice(6)) : null;
|
||||
@@ -5621,7 +5633,7 @@ const IssueChatComposer = forwardRef<
|
||||
noneLabel="No responsible"
|
||||
searchPlaceholder="Search responsible..."
|
||||
emptyMessage="No responsible found."
|
||||
onChange={setReassignTarget}
|
||||
onChange={selectAssignee}
|
||||
className="h-8 text-xs"
|
||||
renderTriggerValue={(option) => {
|
||||
if (!option)
|
||||
|
||||
@@ -65,14 +65,15 @@ describe("IssueFiltersPopover", () => {
|
||||
agents={[{ id: "agent-1", name: "Agent One" }]}
|
||||
projects={[{ id: "project-1", name: "Project One" }]}
|
||||
labels={[{ id: "label-1", name: "Bug", color: "#ff0000" }]}
|
||||
workspaces={[{ id: "workspace-1", name: "Workspace One" }]}
|
||||
enableRoutineVisibilityFilter
|
||||
enableAgentCreatedVisibilityFilter
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const popoverContent = container.querySelector("[data-testid='popover-content']");
|
||||
expect(popoverContent).not.toBeNull();
|
||||
expect(popoverContent?.querySelector('[data-filter-options="workspaces"]')).toBeNull();
|
||||
expect(popoverContent?.textContent).not.toContain("Workspace");
|
||||
expect(popoverContent?.className).toContain("overflow-y-auto");
|
||||
expect(popoverContent?.className).toContain("max-h-(--sz-calc-9)");
|
||||
expect(popoverContent?.querySelectorAll(".overflow-y-auto").length).toBe(0);
|
||||
@@ -97,8 +98,7 @@ describe("IssueFiltersPopover", () => {
|
||||
agents={[{ id: "agent-1", name: "Agent One" }]}
|
||||
projects={[{ id: "project-1", name: "Project One" }]}
|
||||
labels={[{ id: "label-1", name: "Bug", color: "#ff0000" }]}
|
||||
workspaces={[{ id: "workspace-1", name: "Workspace One" }]}
|
||||
enableRoutineVisibilityFilter
|
||||
enableAgentCreatedVisibilityFilter
|
||||
/>,
|
||||
);
|
||||
});
|
||||
@@ -108,6 +108,9 @@ describe("IssueFiltersPopover", () => {
|
||||
// Status section still renders, Priority section is gated off (PAP-411).
|
||||
expect(popoverContent?.textContent).toContain("Status");
|
||||
expect(popoverContent?.textContent).not.toContain("Priority");
|
||||
const creationToggle = Array.from(popoverContent?.querySelectorAll("label") ?? []).find((label) => label.textContent?.includes("show agent-created tasks"));
|
||||
expect(creationToggle?.textContent).toBe("show agent-created tasks");
|
||||
expect(creationToggle?.querySelector("input")?.checked).toBe(false);
|
||||
});
|
||||
|
||||
it("searches long option lists while the popover remains the only scroll owner", () => {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Badge } from "@/components/ui/badge";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { Bot, Check, Filter, HardDrive, Search, User, X } from "lucide-react";
|
||||
import { Bot, Check, Filter, Search, User, X } from "lucide-react";
|
||||
import { PriorityIcon } from "./PriorityIcon";
|
||||
import { SHOW_TASK_PRIORITY_UI } from "../lib/ui-flags";
|
||||
import { StatusIcon } from "./StatusIcon";
|
||||
@@ -43,11 +43,6 @@ type LabelOption = {
|
||||
color: string;
|
||||
};
|
||||
|
||||
type WorkspaceOption = {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
type CreatorOption = {
|
||||
id: string;
|
||||
label: string;
|
||||
@@ -113,10 +108,9 @@ export function IssueFiltersPopover({
|
||||
labels,
|
||||
currentUserId,
|
||||
enableExternalObjectFilters = true,
|
||||
enableRoutineVisibilityFilter = false,
|
||||
enableAgentCreatedVisibilityFilter = false,
|
||||
buttonVariant = "ghost",
|
||||
iconOnly = false,
|
||||
workspaces,
|
||||
creators,
|
||||
presentation = "legacy",
|
||||
inboxScopeFilters,
|
||||
@@ -129,10 +123,9 @@ export function IssueFiltersPopover({
|
||||
labels?: LabelOption[];
|
||||
currentUserId?: string | null;
|
||||
enableExternalObjectFilters?: boolean;
|
||||
enableRoutineVisibilityFilter?: boolean;
|
||||
enableAgentCreatedVisibilityFilter?: boolean;
|
||||
buttonVariant?: "ghost" | "outline";
|
||||
iconOnly?: boolean;
|
||||
workspaces?: WorkspaceOption[];
|
||||
creators?: CreatorOption[];
|
||||
presentation?: "legacy" | "streamlined";
|
||||
inboxScopeFilters?: InboxScopeFilters;
|
||||
@@ -142,7 +135,6 @@ export function IssueFiltersPopover({
|
||||
const [assigneeSearch, setAssigneeSearch] = useState("");
|
||||
const [projectSearch, setProjectSearch] = useState("");
|
||||
const [labelSearch, setLabelSearch] = useState("");
|
||||
const [workspaceSearch, setWorkspaceSearch] = useState("");
|
||||
const visibleAgents = useMemo(
|
||||
() => searchIssueFilterOptions(agents, assigneeSearch, (option) => option.name),
|
||||
[agents, assigneeSearch],
|
||||
@@ -155,10 +147,6 @@ export function IssueFiltersPopover({
|
||||
() => searchIssueFilterOptions(labels, labelSearch, (option) => option.name),
|
||||
[labels, labelSearch],
|
||||
);
|
||||
const visibleWorkspaces = useMemo(
|
||||
() => searchIssueFilterOptions(workspaces, workspaceSearch, (option) => option.name),
|
||||
[workspaces, workspaceSearch],
|
||||
);
|
||||
const creatorOptions = creators ?? [];
|
||||
const creatorOptionById = useMemo(
|
||||
() => new Map(creatorOptions.map((option) => [option.id, option])),
|
||||
@@ -490,27 +478,6 @@ export function IssueFiltersPopover({
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{workspaces && workspaces.length > 0 ? (
|
||||
<div className="space-y-1">
|
||||
<span className="text-xs text-muted-foreground">Workspace</span>
|
||||
{streamlined && workspaces.length > SEARCHABLE_FILTER_THRESHOLD ? (
|
||||
<FilterOptionSearch value={workspaceSearch} onChange={setWorkspaceSearch} label="Workspaces" />
|
||||
) : null}
|
||||
<div data-filter-options="workspaces" className={streamlined ? "space-y-0.5" : "max-h-32 space-y-0.5 overflow-y-auto"}>
|
||||
{(streamlined ? visibleWorkspaces : workspaces).map((workspace) => (
|
||||
<label key={workspace.id} className="flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1 hover:bg-accent/50">
|
||||
<Checkbox
|
||||
checked={state.workspaces.includes(workspace.id)}
|
||||
onCheckedChange={() => onChange({ workspaces: toggleIssueFilterValue(state.workspaces, workspace.id) })}
|
||||
/>
|
||||
<HardDrive className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<span className="text-sm">{workspace.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{enableExternalObjectFilters ? (
|
||||
<div className="space-y-1">
|
||||
<span className="text-xs text-muted-foreground">External object status</span>
|
||||
@@ -553,13 +520,13 @@ export function IssueFiltersPopover({
|
||||
/>
|
||||
<span className="text-sm">Live runs only</span>
|
||||
</label>
|
||||
{enableRoutineVisibilityFilter ? (
|
||||
{enableAgentCreatedVisibilityFilter ? (
|
||||
<label className="flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1 hover:bg-accent/50">
|
||||
<Checkbox
|
||||
checked={state.hideRoutineExecutions}
|
||||
onCheckedChange={(checked) => onChange({ hideRoutineExecutions: checked === true })}
|
||||
checked={state.showAgentCreatedTasks}
|
||||
onCheckedChange={(checked) => onChange({ showAgentCreatedTasks: checked === true })}
|
||||
/>
|
||||
<span className="text-sm">Hide routine runs</span>
|
||||
<span className="text-sm">show agent-created tasks</span>
|
||||
</label>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -16,6 +16,7 @@ import type { Issue, IssueDocument } from "@paperclipai/shared";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getLastProjectId } from "../lib/recent-projects";
|
||||
import { IssueProperties } from "./IssueProperties";
|
||||
import { applyOptimisticIssueFieldUpdate } from "../lib/optimistic-issue-comments";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
|
||||
const mockAgentsApi = vi.hoisted(() => ({
|
||||
@@ -439,6 +440,18 @@ function createExecutionState(overrides: Partial<IssueExecutionState> = {}): Iss
|
||||
};
|
||||
}
|
||||
|
||||
function createRelation(id: string, identifier: string, title: string, status: Issue["status"] = "todo") {
|
||||
return {
|
||||
id,
|
||||
identifier,
|
||||
title,
|
||||
status,
|
||||
priority: "medium" as const,
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
};
|
||||
}
|
||||
|
||||
function renderPropertiesWithQueryClient(container: HTMLDivElement, props: ComponentProps<typeof IssueProperties>, hiddenSettings: string[] = []) {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
@@ -663,24 +676,8 @@ describe("IssueProperties", () => {
|
||||
});
|
||||
|
||||
it("stacks property chips vertically and aligns each label with the first chip", async () => {
|
||||
const blockedBy = Array.from({ length: 3 }, (_, index) => ({
|
||||
id: `blocker-${index + 1}`,
|
||||
identifier: `BLOCK-${index + 1}`,
|
||||
title: `Blocker ${index + 1}`,
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
})) as NonNullable<Issue["blockedBy"]>;
|
||||
const blocks = Array.from({ length: 3 }, (_, index) => ({
|
||||
id: `blocked-${index + 1}`,
|
||||
identifier: `BLOCKED-${index + 1}`,
|
||||
title: `Blocked task ${index + 1}`,
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
})) as NonNullable<Issue["blocks"]>;
|
||||
const blockedBy = Array.from({ length: 3 }, (_, index) => (createRelation(`blocker-${index + 1}`, `BLOCK-${index + 1}`, `Blocker ${index + 1}`))) as NonNullable<Issue["blockedBy"]>;
|
||||
const blocks = Array.from({ length: 3 }, (_, index) => (createRelation(`blocked-${index + 1}`, `BLOCKED-${index + 1}`, `Blocked task ${index + 1}`))) as NonNullable<Issue["blocks"]>;
|
||||
const labels = Array.from({ length: 3 }, (_, index) => createLabel({
|
||||
id: `label-${index + 1}`,
|
||||
name: `Label ${index + 1}`,
|
||||
@@ -1416,15 +1413,7 @@ describe("IssueProperties", () => {
|
||||
const root = renderProperties(container, {
|
||||
issue: createIssue({
|
||||
blockedBy: [
|
||||
{
|
||||
id: "issue-2",
|
||||
identifier: "PAP-2",
|
||||
title: "Existing blocker",
|
||||
status: "in_progress",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
},
|
||||
createRelation("issue-2", "PAP-2", "Existing blocker", "in_progress"),
|
||||
],
|
||||
}),
|
||||
childIssues: [],
|
||||
@@ -1516,24 +1505,8 @@ describe("IssueProperties", () => {
|
||||
const root = renderProperties(container, {
|
||||
issue: createIssue({
|
||||
blockedBy: [
|
||||
{
|
||||
id: "issue-2",
|
||||
identifier: "PAP-2",
|
||||
title: "Existing blocker",
|
||||
status: "in_progress",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
},
|
||||
{
|
||||
id: "issue-4",
|
||||
identifier: "PAP-4",
|
||||
title: "Keep blocker",
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
},
|
||||
createRelation("issue-2", "PAP-2", "Existing blocker", "in_progress"),
|
||||
createRelation("issue-4", "PAP-4", "Keep blocker"),
|
||||
],
|
||||
}),
|
||||
childIssues: [],
|
||||
@@ -1569,24 +1542,8 @@ describe("IssueProperties", () => {
|
||||
const root = renderProperties(container, {
|
||||
issue: createIssue({
|
||||
blockedBy: [
|
||||
{
|
||||
id: "issue-2",
|
||||
identifier: "PAP-2",
|
||||
title: "Existing blocker",
|
||||
status: "in_progress",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
},
|
||||
{
|
||||
id: "issue-4",
|
||||
identifier: "PAP-4",
|
||||
title: "Keep blocker",
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
},
|
||||
createRelation("issue-2", "PAP-2", "Existing blocker", "in_progress"),
|
||||
createRelation("issue-4", "PAP-4", "Keep blocker"),
|
||||
],
|
||||
}),
|
||||
childIssues: [],
|
||||
@@ -1617,15 +1574,7 @@ describe("IssueProperties", () => {
|
||||
});
|
||||
|
||||
it("summarizes long blocked-by and subtask relationships in their picker triggers", async () => {
|
||||
const blockedBy = Array.from({ length: 7 }, (_, index) => ({
|
||||
id: `blocker-${index + 1}`,
|
||||
identifier: `BLOCK-${index + 1}`,
|
||||
title: `Blocker ${index + 1}`,
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
})) as NonNullable<Issue["blockedBy"]>;
|
||||
const blockedBy = Array.from({ length: 7 }, (_, index) => (createRelation(`blocker-${index + 1}`, `BLOCK-${index + 1}`, `Blocker ${index + 1}`))) as NonNullable<Issue["blockedBy"]>;
|
||||
const childIssues = Array.from({ length: 7 }, (_, index) => createIssue({
|
||||
id: `child-${index + 1}`,
|
||||
identifier: `SUB-${index + 1}`,
|
||||
@@ -1677,15 +1626,7 @@ describe("IssueProperties", () => {
|
||||
enableTaskWatchdogs: false,
|
||||
enableClassicTaskInterface: true,
|
||||
});
|
||||
const blocking = Array.from({ length: 7 }, (_, index) => ({
|
||||
id: `blocking-${index + 1}`,
|
||||
identifier: `BLOCKING-${index + 1}`,
|
||||
title: `Blocking issue ${index + 1}`,
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
})) as NonNullable<Issue["blocks"]>;
|
||||
const blocking = Array.from({ length: 7 }, (_, index) => (createRelation(`blocking-${index + 1}`, `BLOCKING-${index + 1}`, `Blocking issue ${index + 1}`))) as NonNullable<Issue["blocks"]>;
|
||||
const relatedIssues = Array.from({ length: 7 }, (_, index) => ({
|
||||
id: `related-${index + 1}`,
|
||||
identifier: `RELATED-${index + 1}`,
|
||||
@@ -1803,15 +1744,7 @@ describe("IssueProperties", () => {
|
||||
});
|
||||
|
||||
it("updates the blocked-by relationship summary when the issue changes", async () => {
|
||||
const blockedBy = Array.from({ length: 7 }, (_, index) => ({
|
||||
id: `blocker-${index + 1}`,
|
||||
identifier: `BLOCK-${index + 1}`,
|
||||
title: `Blocker ${index + 1}`,
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
})) as NonNullable<Issue["blockedBy"]>;
|
||||
const blockedBy = Array.from({ length: 7 }, (_, index) => (createRelation(`blocker-${index + 1}`, `BLOCK-${index + 1}`, `Blocker ${index + 1}`))) as NonNullable<Issue["blockedBy"]>;
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
@@ -1940,6 +1873,36 @@ describe("IssueProperties", () => {
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it("changes only project organization while preserving the bound workspace", async () => {
|
||||
mockProjectsApi.list.mockResolvedValue([createProject({ name: "Target Project" })]);
|
||||
const workspace = createExecutionWorkspace({ projectId: null, projectWorkspaceId: null });
|
||||
const issue = createIssue({
|
||||
executionWorkspaceId: workspace.id,
|
||||
currentExecutionWorkspace: workspace,
|
||||
});
|
||||
const onUpdate = vi.fn();
|
||||
const root = renderProperties(container, { issue, childIssues: [], onUpdate, inline: true });
|
||||
await flush();
|
||||
await act(() => findRowTrigger(container, "Project")!.click());
|
||||
const project = [...document.querySelectorAll<HTMLButtonElement>("button")]
|
||||
.find((button) => button.textContent?.trim() === "Target Project")!;
|
||||
act(() => project.click());
|
||||
expect(onUpdate).toHaveBeenLastCalledWith({ projectId: "project-1" });
|
||||
const assigned = applyOptimisticIssueFieldUpdate(issue, onUpdate.mock.lastCall![0])!;
|
||||
expect(assigned.executionWorkspaceId).toBe(workspace.id);
|
||||
expect(assigned.currentExecutionWorkspace).toBe(workspace);
|
||||
await act(() => findRowTrigger(container, "Project")!.click());
|
||||
const none = [...document.querySelectorAll<HTMLButtonElement>("button")]
|
||||
.find((button) => button.textContent?.trim() === "No project")!;
|
||||
act(() => none.click());
|
||||
expect(onUpdate).toHaveBeenLastCalledWith({ projectId: null });
|
||||
const cleared = applyOptimisticIssueFieldUpdate(assigned, onUpdate.mock.lastCall![0])!;
|
||||
expect(cleared.executionWorkspaceId).toBe(workspace.id);
|
||||
expect(cleared.currentExecutionWorkspace).toBe(workspace);
|
||||
expect(cleared.currentExecutionWorkspace?.cwd).toBe(workspace.cwd);
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("shows a green service link above the workspace row for a live non-main workspace", async () => {
|
||||
mockProjectsApi.list.mockResolvedValue([createProject()]);
|
||||
const serviceUrl = "http://127.0.0.1:62475";
|
||||
@@ -2134,30 +2097,14 @@ describe("IssueProperties", () => {
|
||||
relatedWork: {
|
||||
outbound: [
|
||||
{
|
||||
issue: {
|
||||
id: "issue-22",
|
||||
identifier: "PAP-22",
|
||||
title: "Related task",
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
},
|
||||
issue: createRelation("issue-22", "PAP-22", "Related task"),
|
||||
mentionCount: 1,
|
||||
sources: [{ kind: "description", sourceRecordId: null, label: "description", matchedText: "PAP-22" }],
|
||||
},
|
||||
],
|
||||
inbound: [
|
||||
{
|
||||
issue: {
|
||||
id: "issue-23",
|
||||
identifier: "PAP-23",
|
||||
title: "Mentions this task",
|
||||
status: "in_progress",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
},
|
||||
issue: createRelation("issue-23", "PAP-23", "Mentions this task", "in_progress"),
|
||||
mentionCount: 1,
|
||||
sources: [{ kind: "description", sourceRecordId: null, label: "description", matchedText: "PAP-1" }],
|
||||
},
|
||||
@@ -2193,65 +2140,25 @@ describe("IssueProperties", () => {
|
||||
const root = renderProperties(container, {
|
||||
issue: createIssue({
|
||||
blockedBy: [
|
||||
{
|
||||
id: "issue-22",
|
||||
identifier: "PAP-22",
|
||||
title: "Blocker",
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
},
|
||||
createRelation("issue-22", "PAP-22", "Blocker"),
|
||||
],
|
||||
blocks: [
|
||||
{
|
||||
id: "issue-33",
|
||||
identifier: "PAP-33",
|
||||
title: "Blocked issue",
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
},
|
||||
createRelation("issue-33", "PAP-33", "Blocked issue"),
|
||||
],
|
||||
relatedWork: {
|
||||
outbound: [
|
||||
{
|
||||
issue: {
|
||||
id: "issue-22",
|
||||
identifier: "PAP-22",
|
||||
title: "Blocker",
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
},
|
||||
issue: createRelation("issue-22", "PAP-22", "Blocker"),
|
||||
mentionCount: 1,
|
||||
sources: [{ kind: "description", sourceRecordId: null, label: "description", matchedText: "PAP-22" }],
|
||||
},
|
||||
{
|
||||
issue: {
|
||||
id: "issue-33",
|
||||
identifier: "PAP-33",
|
||||
title: "Blocked issue",
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
},
|
||||
issue: createRelation("issue-33", "PAP-33", "Blocked issue"),
|
||||
mentionCount: 1,
|
||||
sources: [{ kind: "description", sourceRecordId: null, label: "description", matchedText: "PAP-33" }],
|
||||
},
|
||||
{
|
||||
issue: {
|
||||
id: "child-44",
|
||||
identifier: "PAP-44",
|
||||
title: "Child issue",
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
},
|
||||
issue: createRelation("child-44", "PAP-44", "Child issue"),
|
||||
mentionCount: 1,
|
||||
sources: [{ kind: "description", sourceRecordId: null, label: "description", matchedText: "PAP-44" }],
|
||||
},
|
||||
|
||||
@@ -1161,3 +1161,10 @@ it("requires export retry for ordinary restoration while keeping explicit board
|
||||
expect(document.body.textContent).not.toContain("Send for review");
|
||||
expect(document.body.textContent).toContain("False positive, done");
|
||||
});
|
||||
|
||||
it("requires owner-stop recovery even for board false-positive dispositions", () => {
|
||||
const node = render(<IssueRecoveryActionCard action={buildAction({ kind: "active_run_watchdog", ownerType: "board",
|
||||
cause: "native_workspace_finalization_owner_unverified" })} onResolve={() => {}} canFalsePositive />);
|
||||
expect(node.querySelector("[data-testid='recovery-action-resolve-trigger']")).toBeNull();
|
||||
expect(node.textContent).not.toContain("False positive");
|
||||
});
|
||||
@@ -1067,6 +1067,7 @@ export function IssueRecoveryActionCard({
|
||||
} satisfies Record<RecoveryCardCardState, string>)[cardState];
|
||||
|
||||
const visibleResolveOptions = RESOLVE_OPTIONS.filter((option) => {
|
||||
if (action.cause === "native_workspace_finalization_owner_unverified") return false;
|
||||
if (isNativeWorkspaceExportRepairCause(action.cause) && ["todo", "done", "in_review"].includes(option.outcome)) return false;
|
||||
if (option.outcome === "todo" && requiresExecutionReconciliation(action.cause)) return false;
|
||||
if (option.boardOnly && !canFalsePositive) return false;
|
||||
|
||||
@@ -214,6 +214,10 @@ describe("IssueThreadInteractionCard", () => {
|
||||
expect(host.querySelector('[data-testid="connection-intent-actions"]')).toBeTruthy();
|
||||
expect(host.textContent).toContain("Connect");
|
||||
expect(host.textContent).toContain("Not now");
|
||||
const labels = Array.from(host.querySelectorAll("button")).map((button) => button.textContent?.trim());
|
||||
expect(labels).toContain("Connect");
|
||||
expect(labels).toContain("Not now");
|
||||
expect(host.textContent).toContain("Access is added only for this agent");
|
||||
const loadButton = Array.from(host.querySelectorAll("button")).find((button) =>
|
||||
button.textContent?.trim() === "Connect",
|
||||
);
|
||||
@@ -241,16 +245,7 @@ describe("IssueThreadInteractionCard", () => {
|
||||
expect(dialog?.textContent).toContain("Complete connection setup without leaving this task.");
|
||||
});
|
||||
|
||||
it("keeps connection resolution controls exclusive to the addressed user", () => {
|
||||
const host = renderCard({
|
||||
interaction: pendingConnectionIntentInteraction,
|
||||
currentUserId: "another-user",
|
||||
});
|
||||
|
||||
expect(host.querySelector('[data-testid="connection-intent-waiting"]')).toBeTruthy();
|
||||
expect(Array.from(host.querySelectorAll("button")).map((button) => button.textContent?.trim())).not.toContain("Connect");
|
||||
expect(host.textContent).not.toContain("Not now");
|
||||
});
|
||||
;
|
||||
|
||||
it("exposes pending question options as selectable radio and checkbox controls", () => {
|
||||
const host = renderCard({
|
||||
@@ -258,6 +253,8 @@ describe("IssueThreadInteractionCard", () => {
|
||||
onSubmitInteractionAnswers: vi.fn(),
|
||||
});
|
||||
|
||||
expect(host.childElementCount).toBeGreaterThan(0);
|
||||
|
||||
const singleGroup = host.querySelector('[role="radiogroup"]');
|
||||
expect(singleGroup?.getAttribute("aria-labelledby")).toBe(
|
||||
"interaction-questions-default-collapse-depth-prompt",
|
||||
@@ -433,15 +430,7 @@ describe("IssueThreadInteractionCard", () => {
|
||||
expect(host.textContent).toBe("");
|
||||
});
|
||||
|
||||
it("still renders a legitimate ask_user_questions card", () => {
|
||||
const host = renderCard({
|
||||
interaction: pendingAskUserQuestionsInteraction,
|
||||
onSubmitInteractionAnswers: vi.fn(),
|
||||
});
|
||||
|
||||
expect(host.childElementCount).toBeGreaterThan(0);
|
||||
expect(host.querySelectorAll('[role="radio"]').length).toBeGreaterThan(0);
|
||||
});
|
||||
;
|
||||
|
||||
it("keeps a closed native select set closed while preserving direct-question defaults", () => {
|
||||
const closed = {
|
||||
@@ -872,9 +861,74 @@ describe("IssueThreadInteractionCard", () => {
|
||||
expect(host.textContent).toContain("Plan v4");
|
||||
expect(targetLinks[0]?.getAttribute("href")).toContain("#document-plan");
|
||||
expect(targetLinks[1]?.getAttribute("href")).toContain("#document-plan");
|
||||
expect(host.querySelector(".lucide-chevron-right")).not.toBeNull();
|
||||
expect(host.textContent).not.toContain("Approve plan");
|
||||
});
|
||||
|
||||
describe("custom request confirmation targets", () => {
|
||||
const prKey = (pull: number) => `github:paperclipai/paperclip-desktop:pull:${pull}`;
|
||||
const unlabeled = (pull: number) => ({ type: "custom" as const, key: prKey(pull) });
|
||||
const labeled = (pull: number) => ({
|
||||
...unlabeled(pull),
|
||||
label: `PR #${pull}`,
|
||||
href: `https://github.com/paperclipai/paperclip-desktop/pull/${pull}`,
|
||||
});
|
||||
const staleTargetChange = (
|
||||
staleTarget: ReturnType<typeof unlabeled>,
|
||||
target: ReturnType<typeof unlabeled>,
|
||||
) => ({
|
||||
...staleTargetRequestConfirmationInteraction,
|
||||
payload: { ...staleTargetRequestConfirmationInteraction.payload, target },
|
||||
result: { version: 1 as const, outcome: "stale_target" as const, staleTarget },
|
||||
});
|
||||
|
||||
it("hides an unlabeled target key on a pending card", () => {
|
||||
const host = renderCard({
|
||||
interaction: {
|
||||
...pendingRequestConfirmationInteraction,
|
||||
payload: { ...pendingRequestConfirmationInteraction.payload, target: unlabeled(16) },
|
||||
},
|
||||
});
|
||||
expect(host.textContent).not.toContain("github:paperclipai");
|
||||
});
|
||||
|
||||
it("links a labeled target on a pending card", () => {
|
||||
const host = renderCard({
|
||||
interaction: {
|
||||
...pendingRequestConfirmationInteraction,
|
||||
payload: { ...pendingRequestConfirmationInteraction.payload, target: labeled(16) },
|
||||
},
|
||||
});
|
||||
const link = host.querySelector(
|
||||
'a[href="https://github.com/paperclipai/paperclip-desktop/pull/16"]',
|
||||
);
|
||||
expect(link?.textContent).toContain("PR #16");
|
||||
expect(host.textContent).not.toContain("github:paperclipai");
|
||||
});
|
||||
|
||||
it("shows no chips or chevron for an unlabeled stale-target change", () => {
|
||||
const host = renderCard({ interaction: staleTargetChange(unlabeled(15), unlabeled(16)) });
|
||||
expect(host.textContent).toContain("Expired by target change");
|
||||
expect(host.textContent).not.toContain("github:paperclipai");
|
||||
expect(host.querySelector(".lucide-chevron-right")).toBeNull();
|
||||
});
|
||||
|
||||
it("links both labeled targets across a stale-target chevron", () => {
|
||||
const host = renderCard({ interaction: staleTargetChange(labeled(15), labeled(16)) });
|
||||
expect(host.textContent).toContain("PR #15");
|
||||
expect(host.textContent).toContain("PR #16");
|
||||
expect(host.textContent).not.toContain("github:paperclipai");
|
||||
expect(host.querySelector(".lucide-chevron-right")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("drops the chevron when only one side of the stale-target change is labeled", () => {
|
||||
const host = renderCard({ interaction: staleTargetChange(unlabeled(15), labeled(16)) });
|
||||
expect(host.textContent).toContain("PR #16");
|
||||
expect(host.textContent).not.toContain("github:paperclipai");
|
||||
expect(host.querySelector(".lucide-chevron-right")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders a jump link for confirmations expired by comment", () => {
|
||||
const host = renderCard({
|
||||
interaction: commentExpiredRequestConfirmationInteraction,
|
||||
@@ -1524,17 +1578,7 @@ describe("IssueThreadInteractionCard connection-authorization card", () => {
|
||||
describe("IssueThreadInteractionCard connection-intent card", () => {
|
||||
const USER_LABELS = new Map([[issueThreadInteractionFixtureMeta.currentUserId, "Carol"]]);
|
||||
|
||||
it("offers the addressed user the shared setup entry point and Not now", () => {
|
||||
const host = renderCard({
|
||||
interaction: pendingConnectionIntentInteraction,
|
||||
currentUserId: issueThreadInteractionFixtureMeta.currentUserId,
|
||||
});
|
||||
expect(host.querySelector('[data-testid="connection-intent-actions"]')).not.toBeNull();
|
||||
const labels = Array.from(host.querySelectorAll("button")).map((button) => button.textContent?.trim());
|
||||
expect(labels).toContain("Connect");
|
||||
expect(labels).toContain("Not now");
|
||||
expect(host.textContent).toContain("Access is added only for this agent");
|
||||
});
|
||||
;
|
||||
|
||||
it("shows another viewer only who it is waiting for", () => {
|
||||
const host = renderCard({
|
||||
@@ -1547,6 +1591,7 @@ describe("IssueThreadInteractionCard connection-intent card", () => {
|
||||
expect(host.querySelector('[data-testid="connection-intent-actions"]')).toBeNull();
|
||||
expect(host.querySelectorAll("button")).toHaveLength(0);
|
||||
expect(host.innerHTML).not.toContain("authorizationUrl");
|
||||
expect(host.textContent).not.toContain("Not now");
|
||||
});
|
||||
|
||||
it("renders retry and connected terminal states without generic confirmation actions", () => {
|
||||
|
||||
@@ -1478,6 +1478,15 @@ function AskUserQuestionsCard({
|
||||
);
|
||||
}
|
||||
|
||||
/** A custom target key is a machine identifier (e.g. `github:org/repo:pull:16`),
|
||||
* not display copy, so unlabeled custom targets render no chip. */
|
||||
function isDisplayableRequestConfirmationTarget(
|
||||
target: RequestConfirmationTarget | null | undefined,
|
||||
): target is RequestConfirmationTarget {
|
||||
if (!target) return false;
|
||||
return target.type !== "custom" || Boolean(target.label);
|
||||
}
|
||||
|
||||
function requestConfirmationTargetLabel(target: RequestConfirmationTarget) {
|
||||
if (target.label) return target.label;
|
||||
const revision = target.revisionNumber ? ` v${target.revisionNumber}` : "";
|
||||
@@ -1511,7 +1520,7 @@ function RequestConfirmationTargetChip({
|
||||
target: RequestConfirmationTarget | null | undefined;
|
||||
tone?: "default" | "subtle";
|
||||
}) {
|
||||
if (!target) return null;
|
||||
if (!isDisplayableRequestConfirmationTarget(target)) return null;
|
||||
|
||||
const href = requestConfirmationTargetHref({ interaction, target });
|
||||
const className = cn(
|
||||
@@ -1652,7 +1661,8 @@ function RequestConfirmationResolution({
|
||||
target={staleTarget}
|
||||
tone="subtle"
|
||||
/>
|
||||
{staleTarget && target ? (
|
||||
{isDisplayableRequestConfirmationTarget(staleTarget)
|
||||
&& isDisplayableRequestConfirmationTarget(target) ? (
|
||||
<ChevronRight className="h-3.5 w-3.5 text-amber-700" />
|
||||
) : null}
|
||||
<RequestConfirmationTargetChip interaction={interaction} target={target} />
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
issueAgeSeparatorLabel,
|
||||
} from "./IssuesList";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { useShowAgentCreatedTasks } from "../hooks/useShowAgentCreatedTasks";
|
||||
import { taskCollectionPreferencesStorageKey } from "../lib/task-collection-preferences";
|
||||
|
||||
const companyState = vi.hoisted(() => ({
|
||||
@@ -24,6 +25,8 @@ const dialogState = vi.hoisted(() => ({
|
||||
}));
|
||||
|
||||
const mockIssuesApi = vi.hoisted(() => ({
|
||||
get: vi.fn(),
|
||||
listAll: vi.fn(),
|
||||
list: vi.fn(),
|
||||
listLabels: vi.fn(),
|
||||
}));
|
||||
@@ -222,7 +225,7 @@ function createIssue(overrides: Partial<Issue> = {}): Issue {
|
||||
assigneeUserId: null,
|
||||
responsibleUserId: null,
|
||||
createdByAgentId: null,
|
||||
createdByUserId: null,
|
||||
createdByUserId: "person",
|
||||
issueNumber: 1,
|
||||
requestDepth: 0,
|
||||
billingCode: null,
|
||||
@@ -354,6 +357,7 @@ describe("IssuesList", () => {
|
||||
mockInstanceSettingsApi.getExperimental.mockReset();
|
||||
mockExternalObjectsApi.getIssueSummaries.mockReset();
|
||||
mockIssuesApi.list.mockResolvedValue([]);
|
||||
mockIssuesApi.listAll.mockResolvedValue([]);
|
||||
mockIssuesApi.listLabels.mockResolvedValue([]);
|
||||
mockAuthApi.getSession.mockResolvedValue({ user: null, session: null });
|
||||
mockAccessApi.listMembers.mockResolvedValue({ members: [], access: {} });
|
||||
@@ -1354,7 +1358,7 @@ describe("IssuesList", () => {
|
||||
agents={[]}
|
||||
projects={[]}
|
||||
viewStateKey="paperclip:test-issues"
|
||||
enableRoutineVisibilityFilter
|
||||
enableAgentCreatedVisibilityFilter
|
||||
onUpdateIssue={() => undefined}
|
||||
/>,
|
||||
container,
|
||||
@@ -1365,11 +1369,13 @@ describe("IssuesList", () => {
|
||||
status: "backlog",
|
||||
limit: 200,
|
||||
includeRoutineExecutions: true,
|
||||
includeAgentCreatedTasks: false,
|
||||
}), { signal: expect.any(AbortSignal) });
|
||||
expect(mockIssuesApi.list).toHaveBeenCalledWith("company-1", expect.objectContaining({
|
||||
status: "done",
|
||||
limit: 200,
|
||||
includeRoutineExecutions: true,
|
||||
includeAgentCreatedTasks: false,
|
||||
}), { signal: expect.any(AbortSignal) });
|
||||
expect(mockKanbanBoard).toHaveBeenLastCalledWith(expect.objectContaining({
|
||||
issues: expect.arrayContaining([
|
||||
@@ -1561,6 +1567,48 @@ describe("IssuesList", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.each([true, false])("retains loaded context while revealing a large automated tree (streamlined=%s)", async (streamlined) => {
|
||||
mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableStreamlinedUi: streamlined });
|
||||
const parent = createIssue({ id: "human-root", createdByUserId: "person", originKind: "manual" });
|
||||
const children = Array.from({ length: 250 }, (_, index) => createIssue({
|
||||
id: `automated-child-${index}`, title: `Automated child ${index}`,
|
||||
parentId: parent.id, createdByUserId: null, createdByAgentId: "agent", originKind: "manual",
|
||||
}));
|
||||
let holdNextRead = false;
|
||||
let releaseRead: (() => void) | undefined;
|
||||
mockIssuesApi.list.mockImplementation(async (_companyId, filters) => {
|
||||
if (filters.parentId !== parent.id) return [];
|
||||
const rows = children.slice(filters.offset ?? 0, (filters.offset ?? 0) + filters.limit);
|
||||
if (holdNextRead) {
|
||||
holdNextRead = false;
|
||||
return new Promise<Issue[]>((resolve) => { releaseRead = () => resolve(rows); });
|
||||
}
|
||||
return rows;
|
||||
});
|
||||
const { root } = renderWithQueryClient(
|
||||
<IssuesList issues={[parent]} agents={[]} projects={[]} viewStateKey="paperclip:test-tree"
|
||||
enableAgentCreatedVisibilityFilter onUpdateIssue={() => undefined} />,
|
||||
container,
|
||||
);
|
||||
await waitForAssertion(() => expect(container.querySelectorAll("[data-testid='issue-row']")).toHaveLength(100));
|
||||
holdNextRead = true;
|
||||
act(() => {
|
||||
setDocumentScrollMetrics({ innerHeight: 600, scrollY: 1500, scrollHeight: 2000 });
|
||||
window.dispatchEvent(new Event("scroll"));
|
||||
});
|
||||
await flushAnimationFrame();
|
||||
await waitForAssertion(() => {
|
||||
expect(releaseRead).toBeDefined();
|
||||
expect(container.querySelectorAll("[data-testid='issue-row']").length).toBeGreaterThanOrEqual(100);
|
||||
});
|
||||
await act(async () => releaseRead!());
|
||||
await waitForAssertion(() => {
|
||||
expect(container.querySelectorAll("[data-testid='issue-row']")).toHaveLength(251);
|
||||
expect(container.textContent).toContain("Automated child 249");
|
||||
}, 60);
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("keeps rendering local issue batches while the user stays near the bottom", async () => {
|
||||
const manyIssues = Array.from({ length: 420 }, (_, index) =>
|
||||
createIssue({
|
||||
@@ -1928,6 +1976,56 @@ describe("IssuesList", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores a saved workspace filter when the page address has no workspace query", async () => {
|
||||
localStorage.setItem(
|
||||
taskCollectionPreferencesStorageKey({
|
||||
companyId: "company-1",
|
||||
collectionKey: "paperclip:test-issues",
|
||||
}),
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
companyId: "company-1",
|
||||
collectionKey: "paperclip:test-issues",
|
||||
viewState: {
|
||||
workspaces: ["workspace-alpha"],
|
||||
},
|
||||
columns: ["id"],
|
||||
}),
|
||||
);
|
||||
const alphaIssue = createIssue({
|
||||
id: "issue-alpha",
|
||||
identifier: "PAP-40",
|
||||
title: "Alpha issue",
|
||||
executionWorkspaceId: "workspace-alpha",
|
||||
});
|
||||
const betaIssue = createIssue({
|
||||
id: "issue-beta",
|
||||
identifier: "PAP-41",
|
||||
title: "Beta issue",
|
||||
executionWorkspaceId: "workspace-beta",
|
||||
});
|
||||
|
||||
const { root } = renderWithQueryClient(
|
||||
<IssuesList
|
||||
issues={[alphaIssue, betaIssue]}
|
||||
agents={[]}
|
||||
projects={[]}
|
||||
viewStateKey="paperclip:test-issues"
|
||||
onUpdateIssue={() => undefined}
|
||||
/>,
|
||||
container,
|
||||
);
|
||||
|
||||
await waitForAssertion(() => {
|
||||
expect(container.textContent).toContain("Alpha issue");
|
||||
expect(container.textContent).toContain("Beta issue");
|
||||
});
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("applies an initial workspace filter from the issues URL state", async () => {
|
||||
const alphaIssue = createIssue({
|
||||
id: "issue-alpha",
|
||||
@@ -1964,11 +2062,17 @@ describe("IssuesList", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("shows routine-backed issues by default and hides them when the routine filter is toggled off", async () => {
|
||||
it.each([true, false])("keeps visibility controls and fetching preferences synchronized (streamlined=%s)", async (streamlined) => {
|
||||
mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableStreamlinedUi: streamlined });
|
||||
function PreferenceProbe() {
|
||||
const included = useShowAgentCreatedTasks("company-1", "paperclip:test-issues");
|
||||
return <span data-testid="creation-preference">{String(included)}</span>;
|
||||
}
|
||||
const manualIssue = createIssue({
|
||||
id: "issue-manual",
|
||||
identifier: "PAP-10",
|
||||
title: "Manual issue",
|
||||
createdByUserId: "person",
|
||||
originKind: "manual",
|
||||
});
|
||||
const routineIssue = createIssue({
|
||||
@@ -1979,20 +2083,20 @@ describe("IssuesList", () => {
|
||||
});
|
||||
|
||||
const { root } = renderWithQueryClient(
|
||||
<IssuesList
|
||||
<><PreferenceProbe /><IssuesList
|
||||
issues={[manualIssue, routineIssue]}
|
||||
agents={[]}
|
||||
projects={[]}
|
||||
viewStateKey="paperclip:test-issues"
|
||||
enableRoutineVisibilityFilter
|
||||
enableAgentCreatedVisibilityFilter
|
||||
onUpdateIssue={() => undefined}
|
||||
/>,
|
||||
/></>,
|
||||
container,
|
||||
);
|
||||
|
||||
await waitForAssertion(() => {
|
||||
expect(container.textContent).toContain("Manual issue");
|
||||
expect(container.textContent).toContain("Routine issue");
|
||||
expect(container.textContent).not.toContain("Routine issue");
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
@@ -2005,26 +2109,38 @@ describe("IssuesList", () => {
|
||||
|
||||
await waitForAssertion(() => {
|
||||
const toggle = Array.from(document.body.querySelectorAll("label")).find(
|
||||
(label) => label.textContent?.includes("Hide routine runs"),
|
||||
(label) => label.textContent?.includes("show agent-created tasks"),
|
||||
);
|
||||
expect(toggle).not.toBeUndefined();
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
const toggle = Array.from(document.body.querySelectorAll("label")).find(
|
||||
(label) => label.textContent?.includes("Hide routine runs"),
|
||||
(label) => label.textContent?.includes("show agent-created tasks"),
|
||||
);
|
||||
toggle?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
await waitForAssertion(() => {
|
||||
expect(container.textContent).toContain("Routine issue");
|
||||
expect(container.querySelector("[data-testid='creation-preference']")?.textContent).toBe("true");
|
||||
});
|
||||
const preferenceKey = taskCollectionPreferencesStorageKey({ companyId: "company-1", collectionKey: "paperclip:test-issues" });
|
||||
const envelope = JSON.parse(localStorage.getItem(preferenceKey)!);
|
||||
await act(async () => {
|
||||
localStorage.setItem(preferenceKey, JSON.stringify({ ...envelope, viewState: { ...envelope.viewState, showAgentCreatedTasks: false } }));
|
||||
window.dispatchEvent(new StorageEvent("storage", { key: preferenceKey }));
|
||||
});
|
||||
await waitForAssertion(() => {
|
||||
expect(container.textContent).not.toContain("Routine issue");
|
||||
expect(container.querySelector("[data-testid='creation-preference']")?.textContent).toBe("false");
|
||||
const label = Array.from(document.body.querySelectorAll("label")).find((element) => element.textContent?.includes("show agent-created tasks"));
|
||||
const checkbox = label?.querySelector("[role='checkbox'], input[type='checkbox']");
|
||||
expect(checkbox).not.toBeNull();
|
||||
expect(checkbox instanceof HTMLInputElement ? checkbox.checked : checkbox?.getAttribute("aria-checked") === "true").toBe(false);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("blurs the search input on Enter without clearing the query", async () => {
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { useShowAgentCreatedTasks } from "../hooks/useShowAgentCreatedTasks";
|
||||
import { useIssueHierarchyContext } from "../hooks/useIssueHierarchyContext";
|
||||
import { includeIssueHierarchyContext } from "../lib/issue-hierarchy-context";
|
||||
import { AgentIdentity } from "@/components/AgentIdentity";
|
||||
import { startTransition, useDeferredValue, useEffect, useMemo, useState, useCallback, useRef } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
@@ -207,6 +210,9 @@ function normalizeIssueViewState(value: unknown): IssueViewState {
|
||||
...defaultViewState,
|
||||
...parsed,
|
||||
...normalizeIssueFilterState(parsed),
|
||||
// A saved workspace selection has no filter control. Drop it on load.
|
||||
// `initialWorkspaces` from the page address is applied after this.
|
||||
workspaces: [],
|
||||
sortField: ["status", "priority", "title", "created", "updated", "workflow"].includes(parsed.sortField ?? "")
|
||||
? parsed.sortField as IssueSortField
|
||||
: defaultViewState.sortField,
|
||||
@@ -492,7 +498,7 @@ interface IssuesListProps {
|
||||
* tokens + wall-clock runtime for every run in the tree.
|
||||
*/
|
||||
parentIssueIdForCostSummary?: string;
|
||||
enableRoutineVisibilityFilter?: boolean;
|
||||
enableAgentCreatedVisibilityFilter?: boolean;
|
||||
hasMoreIssues?: boolean;
|
||||
isLoadingMoreIssues?: boolean;
|
||||
mutedIssueIds?: Set<string>;
|
||||
@@ -732,7 +738,7 @@ function StreamlinedIssuesList({
|
||||
defaultSortField,
|
||||
showProgressSummary = false,
|
||||
parentIssueIdForCostSummary,
|
||||
enableRoutineVisibilityFilter = false,
|
||||
enableAgentCreatedVisibilityFilter = false,
|
||||
hasMoreIssues = false,
|
||||
isLoadingMoreIssues = false,
|
||||
mutedIssueIds,
|
||||
@@ -819,10 +825,17 @@ function StreamlinedIssuesList({
|
||||
initialStatuses,
|
||||
),
|
||||
);
|
||||
const showAgentCreatedTasks = useShowAgentCreatedTasks(selectedCompanyId, viewStateKey);
|
||||
useEffect(() => {
|
||||
if (!enableAgentCreatedVisibilityFilter) return;
|
||||
setViewState((previous) => previous.showAgentCreatedTasks === showAgentCreatedTasks
|
||||
? previous : { ...previous, showAgentCreatedTasks });
|
||||
}, [enableAgentCreatedVisibilityFilter, showAgentCreatedTasks]);
|
||||
const [assigneePickerIssueId, setAssigneePickerIssueId] = useState<string | null>(null);
|
||||
const [assigneeSearch, setAssigneeSearch] = useState("");
|
||||
const [issueSearch, setIssueSearch] = useState(initialSearch ?? "");
|
||||
const [renderedIssueRowLimit, setRenderedIssueRowLimit] = useState(INITIAL_ISSUE_ROW_RENDER_LIMIT);
|
||||
const [hierarchyRowBudget, setHierarchyRowBudget] = useState(INITIAL_ISSUE_ROW_RENDER_LIMIT);
|
||||
const [visibleIssueColumns, setVisibleIssueColumns] = useState<InboxIssueColumn[]>(initialPreferences.columns);
|
||||
const renderedIssueIdsRef = useRef("");
|
||||
const initialServerFillRequestedRef = useRef(false);
|
||||
@@ -892,6 +905,8 @@ function StreamlinedIssuesList({
|
||||
// Deleted or reassigned issues leave orphan IDs in localStorage; this keeps
|
||||
// the stored array bounded to only current parent IDs.
|
||||
useEffect(() => {
|
||||
// Contextual children are loaded separately from independent results.
|
||||
if (enableAgentCreatedVisibilityFilter) return;
|
||||
const parentIds = new Set(issues.map((i) => i.parentId).filter(Boolean) as string[]);
|
||||
const pruned = viewState.collapsedParents.filter((id) => parentIds.has(id));
|
||||
if (pruned.length !== viewState.collapsedParents.length) {
|
||||
@@ -906,7 +921,8 @@ function StreamlinedIssuesList({
|
||||
searchFilters ?? {},
|
||||
"compact",
|
||||
ISSUE_SEARCH_RESULT_LIMIT,
|
||||
enableRoutineVisibilityFilter ? "with-routine-executions" : "without-routine-executions",
|
||||
enableAgentCreatedVisibilityFilter ? "with-routine-executions" : "without-routine-executions",
|
||||
enableAgentCreatedVisibilityFilter ? viewState.showAgentCreatedTasks : undefined,
|
||||
],
|
||||
queryFn: ({ signal }) =>
|
||||
issuesApi.listCompact(selectedCompanyId!, {
|
||||
@@ -914,7 +930,7 @@ function StreamlinedIssuesList({
|
||||
projectId,
|
||||
limit: ISSUE_SEARCH_RESULT_LIMIT,
|
||||
...searchFilters,
|
||||
...(enableRoutineVisibilityFilter ? { includeRoutineExecutions: true } : {}),
|
||||
...(enableAgentCreatedVisibilityFilter ? { includeRoutineExecutions: true, includeAgentCreatedTasks: viewState.showAgentCreatedTasks } : {}),
|
||||
}, { signal }).then((rows) => rows as Issue[]),
|
||||
enabled: !!selectedCompanyId && normalizedIssueSearch.length > 0 && !searchWithinLoadedIssues,
|
||||
placeholderData: (previousData) => previousData,
|
||||
@@ -930,7 +946,8 @@ function StreamlinedIssuesList({
|
||||
searchFilters ?? {},
|
||||
"compact",
|
||||
ISSUE_BOARD_COLUMN_RESULT_LIMIT,
|
||||
enableRoutineVisibilityFilter ? "with-routine-executions" : "without-routine-executions",
|
||||
enableAgentCreatedVisibilityFilter ? "with-routine-executions" : "without-routine-executions",
|
||||
enableAgentCreatedVisibilityFilter ? viewState.showAgentCreatedTasks : undefined,
|
||||
],
|
||||
queryFn: ({ signal }: { signal: AbortSignal }) =>
|
||||
issuesApi.listCompact(selectedCompanyId!, {
|
||||
@@ -939,7 +956,7 @@ function StreamlinedIssuesList({
|
||||
projectId,
|
||||
status,
|
||||
limit: ISSUE_BOARD_COLUMN_RESULT_LIMIT,
|
||||
...(enableRoutineVisibilityFilter ? { includeRoutineExecutions: true } : {}),
|
||||
...(enableAgentCreatedVisibilityFilter ? { includeRoutineExecutions: true, includeAgentCreatedTasks: viewState.showAgentCreatedTasks } : {}),
|
||||
}, { signal }).then((rows) => rows as Issue[]),
|
||||
enabled: !!selectedCompanyId && viewState.viewMode === "board" && !searchWithinLoadedIssues,
|
||||
placeholderData: (previousData: Issue[] | undefined) => previousData,
|
||||
@@ -1043,16 +1060,6 @@ function StreamlinedIssuesList({
|
||||
return map;
|
||||
}, [defaultProjectWorkspaceIds, executionWorkspaceById, projectWorkspaceById]);
|
||||
|
||||
const workspaceOptions = useMemo(() => {
|
||||
const options = new Map<string, string>();
|
||||
for (const [workspaceId, workspaceName] of workspaceNameMap) {
|
||||
options.set(workspaceId, workspaceName);
|
||||
}
|
||||
return [...options.entries()]
|
||||
.sort((a, b) => a[1].localeCompare(b[1]))
|
||||
.map(([id, name]) => ({ id, name }));
|
||||
}, [workspaceNameMap]);
|
||||
|
||||
const creatorOptions = useMemo<CreatorOption[]>(() => {
|
||||
const options = new Map<string, CreatorOption>();
|
||||
const knownAgentIds = new Set<string>();
|
||||
@@ -1209,7 +1216,7 @@ function StreamlinedIssuesList({
|
||||
searchScopedIssues,
|
||||
viewState,
|
||||
currentUserId,
|
||||
enableRoutineVisibilityFilter,
|
||||
enableAgentCreatedVisibilityFilter,
|
||||
liveIssueIds,
|
||||
issueFilterContext,
|
||||
);
|
||||
@@ -1218,7 +1225,7 @@ function StreamlinedIssuesList({
|
||||
searchScopedIssues,
|
||||
viewState,
|
||||
currentUserId,
|
||||
enableRoutineVisibilityFilter,
|
||||
enableAgentCreatedVisibilityFilter,
|
||||
liveIssueIds,
|
||||
issueFilterContext,
|
||||
]);
|
||||
@@ -1276,7 +1283,7 @@ function StreamlinedIssuesList({
|
||||
enabled: !!selectedCompanyId,
|
||||
});
|
||||
|
||||
const activeFilterCount = countActiveIssueFilters(viewState, enableRoutineVisibilityFilter);
|
||||
const activeFilterCount = countActiveIssueFilters(viewState, enableAgentCreatedVisibilityFilter);
|
||||
const boardHighVolume = viewState.viewMode === "board" && filtered.length > KANBAN_BOARD_HIGH_VOLUME_THRESHOLD;
|
||||
const boardCompactCards =
|
||||
viewState.boardCardDensity === "compact"
|
||||
@@ -1294,7 +1301,13 @@ function StreamlinedIssuesList({
|
||||
|| viewState.boardColdLaneMode !== "auto"
|
||||
|| viewState.boardColumnPageSize !== KANBAN_COLUMN_DEFAULT_PAGE_SIZE;
|
||||
|
||||
const groupedContent = useMemo(() => {
|
||||
const hierarchyEnabled = enableAgentCreatedVisibilityFilter && !viewState.showAgentCreatedTasks && viewState.nestingEnabled && viewState.viewMode === "list";
|
||||
const hierarchy = useIssueHierarchyContext(
|
||||
selectedCompanyId, filtered.slice(0, renderedIssueRowLimit), viewState.collapsedParents,
|
||||
hierarchyEnabled,
|
||||
hierarchyRowBudget,
|
||||
);
|
||||
const baseGroupedContent = useMemo(() => {
|
||||
if (viewState.groupBy === "none") {
|
||||
return [{ key: "__all", label: null as string | null, items: filtered }];
|
||||
}
|
||||
@@ -1386,6 +1399,14 @@ function StreamlinedIssuesList({
|
||||
companyUserLabelMap,
|
||||
projectById,
|
||||
]);
|
||||
const groupedContent = useMemo(() => baseGroupedContent.map((group) => ({
|
||||
...group,
|
||||
items: enableAgentCreatedVisibilityFilter && !viewState.showAgentCreatedTasks && viewState.nestingEnabled && viewState.viewMode === "list"
|
||||
? includeIssueHierarchyContext(group.items, [...issues, ...hierarchy.issues])
|
||||
: group.items,
|
||||
})), [baseGroupedContent, hierarchy.issues, issues, enableAgentCreatedVisibilityFilter, viewState.showAgentCreatedTasks, viewState.nestingEnabled, viewState.viewMode]);
|
||||
const visibleListRowCount = groupedContent.reduce((total, group) => total + group.items.length, 0);
|
||||
|
||||
|
||||
// Flattened visible order (group headers, then tree DFS per group —
|
||||
// collapsed groups keep their header entry but skip their rows) — must
|
||||
@@ -1575,31 +1596,41 @@ function StreamlinedIssuesList({
|
||||
const previousIssueIds = renderedIssueIdsRef.current;
|
||||
renderedIssueIdsRef.current = nextIssueIds;
|
||||
|
||||
const sameResultsOrAppend = previousIssueIds.length > 0 && nextIssueIds.startsWith(previousIssueIds);
|
||||
if (!sameResultsOrAppend) setHierarchyRowBudget(INITIAL_ISSUE_ROW_RENDER_LIMIT);
|
||||
setRenderedIssueRowLimit((current) => {
|
||||
const nextInitialLimit = Math.min(filtered.length, INITIAL_ISSUE_ROW_RENDER_LIMIT);
|
||||
const listAppended = previousIssueIds.length > 0
|
||||
&& nextIssueIds.startsWith(previousIssueIds)
|
||||
&& filtered.length >= current;
|
||||
if (listAppended) return Math.min(filtered.length, Math.max(current, nextInitialLimit));
|
||||
const nextInitialLimit = Math.min(visibleListRowCount, INITIAL_ISSUE_ROW_RENDER_LIMIT);
|
||||
// Context arrives asynchronously and must not undo a reveal request.
|
||||
if (hierarchyEnabled && sameResultsOrAppend) return Math.max(current, nextInitialLimit);
|
||||
const listAppended = sameResultsOrAppend && visibleListRowCount >= current;
|
||||
if (listAppended) return Math.min(visibleListRowCount, Math.max(current, nextInitialLimit));
|
||||
return nextInitialLimit;
|
||||
});
|
||||
}, [filtered, viewState.viewMode]);
|
||||
}, [filtered, visibleListRowCount, viewState.viewMode, hierarchyEnabled]);
|
||||
|
||||
const hasMoreRenderedRows = viewState.viewMode === "list" && renderedIssueRowLimit < filtered.length;
|
||||
const remainingIssueRowCount = Math.max(filtered.length - renderedIssueRowLimit, 0);
|
||||
const hasMoreHierarchyRows = hierarchyEnabled && hierarchy.hasMore;
|
||||
const hasMoreRenderedRows = viewState.viewMode === "list" && renderedIssueRowLimit < visibleListRowCount;
|
||||
const remainingIssueRowCount = Math.max(visibleListRowCount - renderedIssueRowLimit, 0);
|
||||
const loadMoreIssueRows = useCallback(() => {
|
||||
if (viewState.viewMode !== "list") return;
|
||||
if (hasMoreHierarchyRows && !hierarchy.isFetching) {
|
||||
setHierarchyRowBudget((current) => current + ISSUE_ROW_RENDER_BATCH_SIZE);
|
||||
setRenderedIssueRowLimit((current) => current + ISSUE_ROW_RENDER_BATCH_SIZE);
|
||||
return;
|
||||
}
|
||||
if (hasMoreRenderedRows) {
|
||||
setRenderedIssueRowLimit((current) => Math.min(filtered.length, current + ISSUE_ROW_RENDER_BATCH_SIZE));
|
||||
setRenderedIssueRowLimit((current) => Math.min(visibleListRowCount, current + ISSUE_ROW_RENDER_BATCH_SIZE));
|
||||
return;
|
||||
}
|
||||
if (hasMoreIssues && !isLoadingMoreIssues) {
|
||||
onLoadMoreIssues?.();
|
||||
}
|
||||
}, [
|
||||
filtered.length,
|
||||
visibleListRowCount,
|
||||
hasMoreIssues,
|
||||
hasMoreRenderedRows,
|
||||
hasMoreHierarchyRows,
|
||||
hierarchy.isFetching,
|
||||
isLoadingMoreIssues,
|
||||
onLoadMoreIssues,
|
||||
viewState.viewMode,
|
||||
@@ -1607,7 +1638,7 @@ function StreamlinedIssuesList({
|
||||
|
||||
const canLoadMoreIssues = viewState.viewMode === "list"
|
||||
&& !isLoading
|
||||
&& (hasMoreRenderedRows || (hasMoreIssues && !isLoadingMoreIssues));
|
||||
&& (hasMoreRenderedRows || (hasMoreHierarchyRows && !hierarchy.isFetching) || (hasMoreIssues && !isLoadingMoreIssues));
|
||||
|
||||
useEffect(() => {
|
||||
if (!canLoadMoreIssues) return;
|
||||
@@ -1918,9 +1949,8 @@ function StreamlinedIssuesList({
|
||||
labels={labels?.map((label) => ({ id: label.id, name: label.name, color: label.color }))}
|
||||
currentUserId={currentUserId}
|
||||
enableExternalObjectFilters={externalObjectsEnabled}
|
||||
enableRoutineVisibilityFilter={enableRoutineVisibilityFilter}
|
||||
enableAgentCreatedVisibilityFilter={enableAgentCreatedVisibilityFilter}
|
||||
iconOnly
|
||||
workspaces={isolatedWorkspacesEnabled ? workspaceOptions : undefined}
|
||||
presentation={rowPresentation === "task" ? "streamlined" : "legacy"}
|
||||
/>
|
||||
|
||||
@@ -2024,7 +2054,8 @@ function StreamlinedIssuesList({
|
||||
Some board columns are showing up to {ISSUE_BOARD_COLUMN_RESULT_LIMIT} tasks. Refine filters or search to reveal the rest.
|
||||
</p>
|
||||
)}
|
||||
{!isLoading && !externalObjectFilterLoading && filtered.length === 0 && viewState.viewMode === "list" && (
|
||||
{hierarchy.error ? <p className="text-sm text-destructive">Failed to load task hierarchy: {hierarchy.error.message}</p> : null}
|
||||
{!isLoading && !externalObjectFilterLoading && visibleListRowCount === 0 && viewState.viewMode === "list" && (
|
||||
<EmptyState
|
||||
icon={CircleDot}
|
||||
message="No tasks match the current filters or search."
|
||||
@@ -2521,13 +2552,13 @@ function StreamlinedIssuesList({
|
||||
</Collapsible>
|
||||
);
|
||||
})}
|
||||
{(remainingIssueRowCount > 0 || hasMoreIssues || isLoadingMoreIssues) && (
|
||||
{(remainingIssueRowCount > 0 || hasMoreHierarchyRows || hasMoreIssues || isLoadingMoreIssues) && (
|
||||
<div className="py-2" data-testid="issues-load-more-sentinel">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isLoadingMoreIssues
|
||||
{isLoadingMoreIssues || (hierarchyEnabled && hierarchy.isFetching)
|
||||
? "Loading more tasks..."
|
||||
: remainingIssueRowCount > 0
|
||||
? `Rendering ${Math.min(renderedIssueRowLimit, filtered.length)} of ${filtered.length} tasks`
|
||||
? `Rendering ${Math.min(renderedIssueRowLimit, visibleListRowCount)} of ${visibleListRowCount} tasks`
|
||||
: "Scroll to load more tasks"}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import { saveTaskCollectionPreferences } from "../lib/task-collection-preferences";
|
||||
import { useShowAgentCreatedTasks } from "../hooks/useShowAgentCreatedTasks";
|
||||
import { useIssueHierarchyContext } from "../hooks/useIssueHierarchyContext";
|
||||
import { includeIssueHierarchyContext } from "../lib/issue-hierarchy-context";
|
||||
import { AgentIdentity } from "@/components/AgentIdentity";
|
||||
import { startTransition, useDeferredValue, useEffect, useMemo, useState, useCallback, useRef } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
@@ -198,6 +202,7 @@ function getViewState(key: string): IssueViewState {
|
||||
...defaultViewState,
|
||||
...parsed,
|
||||
...normalizeIssueFilterState(parsed),
|
||||
workspaces: [],
|
||||
boardCardDensity: normalizeBoardCardDensity(parsed.boardCardDensity),
|
||||
boardColdLaneMode: normalizeBoardColdLaneMode(parsed.boardColdLaneMode),
|
||||
boardColumnPageSize: normalizeBoardColumnPageSize(parsed.boardColumnPageSize),
|
||||
@@ -207,10 +212,6 @@ function getViewState(key: string): IssueViewState {
|
||||
return { ...defaultViewState };
|
||||
}
|
||||
|
||||
function saveViewState(key: string, state: IssueViewState) {
|
||||
localStorage.setItem(key, JSON.stringify(state));
|
||||
}
|
||||
|
||||
function getInitialViewState(
|
||||
key: string,
|
||||
initialAssignees?: string[],
|
||||
@@ -268,17 +269,6 @@ function loadIssueColumns(key: string): InboxIssueColumn[] {
|
||||
}
|
||||
}
|
||||
|
||||
function saveIssueColumns(key: string, columns: InboxIssueColumn[]) {
|
||||
try {
|
||||
localStorage.setItem(
|
||||
getIssueColumnsStorageKey(key),
|
||||
JSON.stringify(normalizeInboxIssueColumns(columns)),
|
||||
);
|
||||
} catch {
|
||||
// Ignore localStorage failures.
|
||||
}
|
||||
}
|
||||
|
||||
function sortIssues(issues: Issue[], state: IssueViewState): Issue[] {
|
||||
if (state.sortField === "workflow") {
|
||||
const ordered = workflowSort(issues);
|
||||
@@ -488,7 +478,7 @@ interface IssuesListProps {
|
||||
* tokens + wall-clock runtime for every run in the tree.
|
||||
*/
|
||||
parentIssueIdForCostSummary?: string;
|
||||
enableRoutineVisibilityFilter?: boolean;
|
||||
enableAgentCreatedVisibilityFilter?: boolean;
|
||||
hasMoreIssues?: boolean;
|
||||
isLoadingMoreIssues?: boolean;
|
||||
mutedIssueIds?: Set<string>;
|
||||
@@ -699,7 +689,7 @@ export function IssuesList({
|
||||
defaultSortField,
|
||||
showProgressSummary = false,
|
||||
parentIssueIdForCostSummary,
|
||||
enableRoutineVisibilityFilter = false,
|
||||
enableAgentCreatedVisibilityFilter = false,
|
||||
hasMoreIssues = false,
|
||||
isLoadingMoreIssues = false,
|
||||
mutedIssueIds,
|
||||
@@ -765,10 +755,17 @@ export function IssuesList({
|
||||
const [viewState, setViewState] = useState<IssueViewState>(() =>
|
||||
getInitialWorkspaceViewState(scopedKey, initialAssignees, initialWorkspaces, defaultSortField),
|
||||
);
|
||||
const showAgentCreatedTasks = useShowAgentCreatedTasks(selectedCompanyId, viewStateKey);
|
||||
useEffect(() => {
|
||||
if (!enableAgentCreatedVisibilityFilter) return;
|
||||
setViewState((previous) => previous.showAgentCreatedTasks === showAgentCreatedTasks
|
||||
? previous : { ...previous, showAgentCreatedTasks });
|
||||
}, [enableAgentCreatedVisibilityFilter, showAgentCreatedTasks]);
|
||||
const [assigneePickerIssueId, setAssigneePickerIssueId] = useState<string | null>(null);
|
||||
const [assigneeSearch, setAssigneeSearch] = useState("");
|
||||
const [issueSearch, setIssueSearch] = useState(initialSearch ?? "");
|
||||
const [renderedIssueRowLimit, setRenderedIssueRowLimit] = useState(INITIAL_ISSUE_ROW_RENDER_LIMIT);
|
||||
const [hierarchyRowBudget, setHierarchyRowBudget] = useState(INITIAL_ISSUE_ROW_RENDER_LIMIT);
|
||||
const [visibleIssueColumns, setVisibleIssueColumns] = useState<InboxIssueColumn[]>(() => loadIssueColumns(scopedKey));
|
||||
const renderedIssueIdsRef = useRef("");
|
||||
const initialServerFillRequestedRef = useRef(false);
|
||||
@@ -800,10 +797,13 @@ export function IssuesList({
|
||||
const updateView = useCallback((patch: Partial<IssueViewState>) => {
|
||||
setViewState((prev) => {
|
||||
const next = { ...prev, ...patch };
|
||||
saveViewState(scopedKey, next);
|
||||
saveTaskCollectionPreferences({
|
||||
companyId: selectedCompanyId ?? "__unscoped__", collectionKey: viewStateKey,
|
||||
legacyViewStorageKey: scopedKey, legacyColumnsStorageKey: getIssueColumnsStorageKey(scopedKey),
|
||||
}, { viewState: next, columns: visibleIssueColumns });
|
||||
return next;
|
||||
});
|
||||
}, [scopedKey]);
|
||||
}, [scopedKey, selectedCompanyId, viewStateKey, visibleIssueColumns]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!experimentalSettingsLoaded || externalObjectsEnabled || viewState.externalObjectStatuses.length === 0) return;
|
||||
@@ -814,6 +814,8 @@ export function IssuesList({
|
||||
// Deleted or reassigned issues leave orphan IDs in localStorage; this keeps
|
||||
// the stored array bounded to only current parent IDs.
|
||||
useEffect(() => {
|
||||
// Contextual children are loaded separately from independent results.
|
||||
if (enableAgentCreatedVisibilityFilter) return;
|
||||
const parentIds = new Set(issues.map((i) => i.parentId).filter(Boolean) as string[]);
|
||||
const pruned = viewState.collapsedParents.filter((id) => parentIds.has(id));
|
||||
if (pruned.length !== viewState.collapsedParents.length) {
|
||||
@@ -828,7 +830,8 @@ export function IssuesList({
|
||||
searchFilters ?? {},
|
||||
"compact",
|
||||
ISSUE_SEARCH_RESULT_LIMIT,
|
||||
enableRoutineVisibilityFilter ? "with-routine-executions" : "without-routine-executions",
|
||||
enableAgentCreatedVisibilityFilter ? "with-routine-executions" : "without-routine-executions",
|
||||
enableAgentCreatedVisibilityFilter ? viewState.showAgentCreatedTasks : undefined,
|
||||
],
|
||||
queryFn: ({ signal }) =>
|
||||
issuesApi.listCompact(selectedCompanyId!, {
|
||||
@@ -836,7 +839,7 @@ export function IssuesList({
|
||||
projectId,
|
||||
limit: ISSUE_SEARCH_RESULT_LIMIT,
|
||||
...searchFilters,
|
||||
...(enableRoutineVisibilityFilter ? { includeRoutineExecutions: true } : {}),
|
||||
...(enableAgentCreatedVisibilityFilter ? { includeRoutineExecutions: true, includeAgentCreatedTasks: viewState.showAgentCreatedTasks } : {}),
|
||||
}, { signal }).then((rows) => rows as Issue[]),
|
||||
enabled: !!selectedCompanyId && normalizedIssueSearch.length > 0 && !searchWithinLoadedIssues,
|
||||
placeholderData: (previousData) => previousData,
|
||||
@@ -852,7 +855,8 @@ export function IssuesList({
|
||||
searchFilters ?? {},
|
||||
"compact",
|
||||
ISSUE_BOARD_COLUMN_RESULT_LIMIT,
|
||||
enableRoutineVisibilityFilter ? "with-routine-executions" : "without-routine-executions",
|
||||
enableAgentCreatedVisibilityFilter ? "with-routine-executions" : "without-routine-executions",
|
||||
enableAgentCreatedVisibilityFilter ? viewState.showAgentCreatedTasks : undefined,
|
||||
],
|
||||
queryFn: ({ signal }: { signal: AbortSignal }) =>
|
||||
issuesApi.listCompact(selectedCompanyId!, {
|
||||
@@ -861,7 +865,7 @@ export function IssuesList({
|
||||
projectId,
|
||||
status,
|
||||
limit: ISSUE_BOARD_COLUMN_RESULT_LIMIT,
|
||||
...(enableRoutineVisibilityFilter ? { includeRoutineExecutions: true } : {}),
|
||||
...(enableAgentCreatedVisibilityFilter ? { includeRoutineExecutions: true, includeAgentCreatedTasks: viewState.showAgentCreatedTasks } : {}),
|
||||
}, { signal }).then((rows) => rows as Issue[]),
|
||||
enabled: !!selectedCompanyId && viewState.viewMode === "board" && !searchWithinLoadedIssues,
|
||||
placeholderData: (previousData: Issue[] | undefined) => previousData,
|
||||
@@ -965,16 +969,6 @@ export function IssuesList({
|
||||
return map;
|
||||
}, [defaultProjectWorkspaceIds, executionWorkspaceById, projectWorkspaceById]);
|
||||
|
||||
const workspaceOptions = useMemo(() => {
|
||||
const options = new Map<string, string>();
|
||||
for (const [workspaceId, workspaceName] of workspaceNameMap) {
|
||||
options.set(workspaceId, workspaceName);
|
||||
}
|
||||
return [...options.entries()]
|
||||
.sort((a, b) => a[1].localeCompare(b[1]))
|
||||
.map(([id, name]) => ({ id, name }));
|
||||
}, [workspaceNameMap]);
|
||||
|
||||
const creatorOptions = useMemo<CreatorOption[]>(() => {
|
||||
const options = new Map<string, CreatorOption>();
|
||||
const knownAgentIds = new Set<string>();
|
||||
@@ -1127,7 +1121,7 @@ export function IssuesList({
|
||||
searchScopedIssues,
|
||||
viewState,
|
||||
currentUserId,
|
||||
enableRoutineVisibilityFilter,
|
||||
enableAgentCreatedVisibilityFilter,
|
||||
liveIssueIds,
|
||||
issueFilterContext,
|
||||
);
|
||||
@@ -1136,7 +1130,7 @@ export function IssuesList({
|
||||
searchScopedIssues,
|
||||
viewState,
|
||||
currentUserId,
|
||||
enableRoutineVisibilityFilter,
|
||||
enableAgentCreatedVisibilityFilter,
|
||||
liveIssueIds,
|
||||
issueFilterContext,
|
||||
]);
|
||||
@@ -1194,7 +1188,7 @@ export function IssuesList({
|
||||
enabled: !!selectedCompanyId,
|
||||
});
|
||||
|
||||
const activeFilterCount = countActiveIssueFilters(viewState, enableRoutineVisibilityFilter);
|
||||
const activeFilterCount = countActiveIssueFilters(viewState, enableAgentCreatedVisibilityFilter);
|
||||
const boardHighVolume = viewState.viewMode === "board" && filtered.length > KANBAN_BOARD_HIGH_VOLUME_THRESHOLD;
|
||||
const boardCompactCards =
|
||||
viewState.boardCardDensity === "compact"
|
||||
@@ -1212,7 +1206,13 @@ export function IssuesList({
|
||||
|| viewState.boardColdLaneMode !== "auto"
|
||||
|| viewState.boardColumnPageSize !== KANBAN_COLUMN_DEFAULT_PAGE_SIZE;
|
||||
|
||||
const groupedContent = useMemo(() => {
|
||||
const hierarchyEnabled = enableAgentCreatedVisibilityFilter && !viewState.showAgentCreatedTasks && viewState.nestingEnabled && viewState.viewMode === "list";
|
||||
const hierarchy = useIssueHierarchyContext(
|
||||
selectedCompanyId, filtered.slice(0, renderedIssueRowLimit), viewState.collapsedParents,
|
||||
hierarchyEnabled,
|
||||
hierarchyRowBudget,
|
||||
);
|
||||
const baseGroupedContent = useMemo(() => {
|
||||
if (viewState.groupBy === "none") {
|
||||
return [{ key: "__all", label: null as string | null, items: filtered }];
|
||||
}
|
||||
@@ -1304,6 +1304,14 @@ export function IssuesList({
|
||||
companyUserLabelMap,
|
||||
projectById,
|
||||
]);
|
||||
const groupedContent = useMemo(() => baseGroupedContent.map((group) => ({
|
||||
...group,
|
||||
items: enableAgentCreatedVisibilityFilter && !viewState.showAgentCreatedTasks && viewState.nestingEnabled && viewState.viewMode === "list"
|
||||
? includeIssueHierarchyContext(group.items, [...issues, ...hierarchy.issues])
|
||||
: group.items,
|
||||
})), [baseGroupedContent, hierarchy.issues, issues, enableAgentCreatedVisibilityFilter, viewState.showAgentCreatedTasks, viewState.nestingEnabled, viewState.viewMode]);
|
||||
const visibleListRowCount = groupedContent.reduce((total, group) => total + group.items.length, 0);
|
||||
|
||||
|
||||
// Flattened visible order (group headers, then tree DFS per group —
|
||||
// collapsed groups keep their header entry but skip their rows) — must
|
||||
@@ -1493,31 +1501,41 @@ export function IssuesList({
|
||||
const previousIssueIds = renderedIssueIdsRef.current;
|
||||
renderedIssueIdsRef.current = nextIssueIds;
|
||||
|
||||
const sameResultsOrAppend = previousIssueIds.length > 0 && nextIssueIds.startsWith(previousIssueIds);
|
||||
if (!sameResultsOrAppend) setHierarchyRowBudget(INITIAL_ISSUE_ROW_RENDER_LIMIT);
|
||||
setRenderedIssueRowLimit((current) => {
|
||||
const nextInitialLimit = Math.min(filtered.length, INITIAL_ISSUE_ROW_RENDER_LIMIT);
|
||||
const listAppended = previousIssueIds.length > 0
|
||||
&& nextIssueIds.startsWith(previousIssueIds)
|
||||
&& filtered.length >= current;
|
||||
if (listAppended) return Math.min(filtered.length, Math.max(current, nextInitialLimit));
|
||||
const nextInitialLimit = Math.min(visibleListRowCount, INITIAL_ISSUE_ROW_RENDER_LIMIT);
|
||||
// Context arrives asynchronously and must not undo a reveal request.
|
||||
if (hierarchyEnabled && sameResultsOrAppend) return Math.max(current, nextInitialLimit);
|
||||
const listAppended = sameResultsOrAppend && visibleListRowCount >= current;
|
||||
if (listAppended) return Math.min(visibleListRowCount, Math.max(current, nextInitialLimit));
|
||||
return nextInitialLimit;
|
||||
});
|
||||
}, [filtered, viewState.viewMode]);
|
||||
}, [filtered, visibleListRowCount, viewState.viewMode, hierarchyEnabled]);
|
||||
|
||||
const hasMoreRenderedRows = viewState.viewMode === "list" && renderedIssueRowLimit < filtered.length;
|
||||
const remainingIssueRowCount = Math.max(filtered.length - renderedIssueRowLimit, 0);
|
||||
const hasMoreHierarchyRows = hierarchyEnabled && hierarchy.hasMore;
|
||||
const hasMoreRenderedRows = viewState.viewMode === "list" && renderedIssueRowLimit < visibleListRowCount;
|
||||
const remainingIssueRowCount = Math.max(visibleListRowCount - renderedIssueRowLimit, 0);
|
||||
const loadMoreIssueRows = useCallback(() => {
|
||||
if (viewState.viewMode !== "list") return;
|
||||
if (hasMoreHierarchyRows && !hierarchy.isFetching) {
|
||||
setHierarchyRowBudget((current) => current + ISSUE_ROW_RENDER_BATCH_SIZE);
|
||||
setRenderedIssueRowLimit((current) => current + ISSUE_ROW_RENDER_BATCH_SIZE);
|
||||
return;
|
||||
}
|
||||
if (hasMoreRenderedRows) {
|
||||
setRenderedIssueRowLimit((current) => Math.min(filtered.length, current + ISSUE_ROW_RENDER_BATCH_SIZE));
|
||||
setRenderedIssueRowLimit((current) => Math.min(visibleListRowCount, current + ISSUE_ROW_RENDER_BATCH_SIZE));
|
||||
return;
|
||||
}
|
||||
if (hasMoreIssues && !isLoadingMoreIssues) {
|
||||
onLoadMoreIssues?.();
|
||||
}
|
||||
}, [
|
||||
filtered.length,
|
||||
visibleListRowCount,
|
||||
hasMoreIssues,
|
||||
hasMoreRenderedRows,
|
||||
hasMoreHierarchyRows,
|
||||
hierarchy.isFetching,
|
||||
isLoadingMoreIssues,
|
||||
onLoadMoreIssues,
|
||||
viewState.viewMode,
|
||||
@@ -1525,7 +1543,7 @@ export function IssuesList({
|
||||
|
||||
const canLoadMoreIssues = viewState.viewMode === "list"
|
||||
&& !isLoading
|
||||
&& (hasMoreRenderedRows || (hasMoreIssues && !isLoadingMoreIssues));
|
||||
&& (hasMoreRenderedRows || (hasMoreHierarchyRows && !hierarchy.isFetching) || (hasMoreIssues && !isLoadingMoreIssues));
|
||||
|
||||
useEffect(() => {
|
||||
if (!canLoadMoreIssues) return;
|
||||
@@ -1633,8 +1651,11 @@ export function IssuesList({
|
||||
const setIssueColumns = useCallback((next: InboxIssueColumn[]) => {
|
||||
const normalized = normalizeInboxIssueColumns(next);
|
||||
setVisibleIssueColumns(normalized);
|
||||
saveIssueColumns(scopedKey, normalized);
|
||||
}, [scopedKey]);
|
||||
saveTaskCollectionPreferences({
|
||||
companyId: selectedCompanyId ?? "__unscoped__", collectionKey: viewStateKey,
|
||||
legacyViewStorageKey: scopedKey, legacyColumnsStorageKey: getIssueColumnsStorageKey(scopedKey),
|
||||
}, { viewState, columns: normalized });
|
||||
}, [scopedKey, selectedCompanyId, viewStateKey, viewState]);
|
||||
|
||||
const toggleIssueColumn = useCallback((column: InboxIssueColumn, enabled: boolean) => {
|
||||
if (enabled) {
|
||||
@@ -1812,9 +1833,8 @@ export function IssuesList({
|
||||
labels={labels?.map((label) => ({ id: label.id, name: label.name, color: label.color }))}
|
||||
currentUserId={currentUserId}
|
||||
enableExternalObjectFilters={externalObjectsEnabled}
|
||||
enableRoutineVisibilityFilter={enableRoutineVisibilityFilter}
|
||||
enableAgentCreatedVisibilityFilter={enableAgentCreatedVisibilityFilter}
|
||||
iconOnly
|
||||
workspaces={isolatedWorkspacesEnabled ? workspaceOptions : undefined}
|
||||
/>
|
||||
|
||||
{/* Sort (list view only) */}
|
||||
@@ -1916,7 +1936,8 @@ export function IssuesList({
|
||||
Some board columns are showing up to {ISSUE_BOARD_COLUMN_RESULT_LIMIT} tasks. Refine filters or search to reveal the rest.
|
||||
</p>
|
||||
)}
|
||||
{!isLoading && !externalObjectFilterLoading && filtered.length === 0 && viewState.viewMode === "list" && (
|
||||
{hierarchy.error ? <p className="text-sm text-destructive">Failed to load task hierarchy: {hierarchy.error.message}</p> : null}
|
||||
{!isLoading && !externalObjectFilterLoading && visibleListRowCount === 0 && viewState.viewMode === "list" && (
|
||||
<EmptyState
|
||||
icon={CircleDot}
|
||||
message="No tasks match the current filters or search."
|
||||
@@ -2359,13 +2380,13 @@ export function IssuesList({
|
||||
</Collapsible>
|
||||
);
|
||||
})}
|
||||
{(remainingIssueRowCount > 0 || hasMoreIssues || isLoadingMoreIssues) && (
|
||||
{(remainingIssueRowCount > 0 || hasMoreHierarchyRows || hasMoreIssues || isLoadingMoreIssues) && (
|
||||
<div className="py-2" data-testid="issues-load-more-sentinel">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isLoadingMoreIssues
|
||||
{isLoadingMoreIssues || (hierarchyEnabled && hierarchy.isFetching)
|
||||
? "Loading more tasks..."
|
||||
: remainingIssueRowCount > 0
|
||||
? `Rendering ${Math.min(renderedIssueRowLimit, filtered.length)} of ${filtered.length} tasks`
|
||||
? `Rendering ${Math.min(renderedIssueRowLimit, visibleListRowCount)} of ${visibleListRowCount} tasks`
|
||||
: "Scroll to load more tasks"}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -40,17 +40,35 @@ afterEach(() => {
|
||||
|
||||
const SAMPLE = "Some text\n\n```ts\nconst answer = 42;\n```\n\nAnd a [link](https://example.com).";
|
||||
|
||||
function tree(children: string, queryClient: QueryClient) {
|
||||
function tree(children: string, queryClient: QueryClient, resolveLinkHref?: (href: string) => string | null) {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ThemeProvider>
|
||||
<MarkdownBody>{children}</MarkdownBody>
|
||||
<MarkdownBody resolveLinkHref={resolveLinkHref}>{children}</MarkdownBody>
|
||||
</ThemeProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("MarkdownBody re-render stability (PAP-10767)", () => {
|
||||
it("uses the current file resolver when the same viewer opens another file", () => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const instructions = "Read the [checklist](./checklist.md).";
|
||||
|
||||
flushSync(() => root?.render(tree(instructions, queryClient, () => "/skills/review/files/first/checklist.md")));
|
||||
expect(container.querySelector("a")?.getAttribute("href")).toBe("/skills/review/files/first/checklist.md");
|
||||
|
||||
flushSync(() => root?.render(tree(instructions, queryClient, () => "/skills/review/files/second/checklist.md")));
|
||||
expect(container.querySelector("a")?.getAttribute("href")).toBe("/skills/review/files/second/checklist.md");
|
||||
|
||||
flushSync(() => root?.render(tree(instructions, queryClient, () => null)));
|
||||
expect(container.querySelector("a")).toBeNull();
|
||||
expect(container.textContent).toContain("Read the checklist.");
|
||||
});
|
||||
|
||||
it("preserves rendered DOM nodes across a parent re-render with unchanged props", () => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
|
||||
@@ -584,9 +584,12 @@ describe("MarkdownBody", () => {
|
||||
it("opens external links in a new tab with safe rel attributes", () => {
|
||||
const html = renderMarkdown("[docs](https://example.com/docs)");
|
||||
|
||||
expect(html).toContain('href="https://example.com/docs"');
|
||||
expect(html).toContain("<a href=\"https://example.com/docs\"");
|
||||
expect(html).toContain('target="_blank"');
|
||||
expect(html).toContain('rel="noopener noreferrer"');
|
||||
expect(html).not.toContain("lucide-github");
|
||||
expect(html).toContain("lucide-external-link");
|
||||
expect(html).toMatch(/<span style="white-space:nowrap">s<svg[^>]*lucide-external-link/);
|
||||
});
|
||||
|
||||
it("opens GitHub links in a new tab", () => {
|
||||
@@ -623,22 +626,9 @@ describe("MarkdownBody", () => {
|
||||
expect(html).toContain('class="lucide lucide-github mr-1 inline h-3.5 w-3.5 align-(--va-0_125em)"');
|
||||
});
|
||||
|
||||
it("does not prefix non-GitHub markdown links with the GitHub icon", () => {
|
||||
const html = renderMarkdown("[docs](https://example.com/docs)");
|
||||
;
|
||||
|
||||
expect(html).toContain('<a href="https://example.com/docs"');
|
||||
expect(html).not.toContain("lucide-github");
|
||||
});
|
||||
|
||||
it("suffixes external links with a new-tab icon glued to the last character", () => {
|
||||
const html = renderMarkdown("[docs](https://example.com/docs)");
|
||||
|
||||
expect(html).toContain('target="_blank"');
|
||||
expect(html).toContain("lucide-external-link");
|
||||
// Last character "s" must sit in a no-wrap span with the icon so the
|
||||
// indicator never wraps away from the link text.
|
||||
expect(html).toMatch(/<span style="white-space:nowrap">s<svg[^>]*lucide-external-link/);
|
||||
});
|
||||
;
|
||||
|
||||
it("does not render the new-tab icon on internal links", () => {
|
||||
const html = renderMarkdown("[settings](/company/settings)");
|
||||
|
||||
@@ -37,7 +37,7 @@ import { StatusIcon } from "./StatusIcon";
|
||||
import { WorkspaceFileLink } from "./WorkspaceFileLink";
|
||||
import { ExternalObjectStatusIcon } from "./ExternalObjectStatusIcon";
|
||||
import {
|
||||
externalObjectCategoryLabel,
|
||||
externalObjectDisplayStatusLabel,
|
||||
externalObjectLivenessLabel,
|
||||
externalObjectProviderLabel,
|
||||
} from "../lib/external-objects";
|
||||
@@ -119,6 +119,8 @@ interface MarkdownBodyProps {
|
||||
externalReferences?: MarkdownExternalReferenceMap;
|
||||
/** Optional resolver for relative image paths (e.g. within export packages) */
|
||||
resolveImageSrc?: (src: string) => string | null;
|
||||
/** Resolve file links to app routes; null leaves the label without a link. */
|
||||
resolveLinkHref?: (href: string) => string | null;
|
||||
/** Called when a user clicks an inline image */
|
||||
onImageClick?: (src: string) => void;
|
||||
/** Keep untrusted decision media inert: image references and diagram source only. */
|
||||
@@ -240,9 +242,10 @@ function MarkdownExternalLink({
|
||||
}) {
|
||||
const provider = externalObjectProviderLabel(reference.providerKey);
|
||||
const displayKey = reference.displayKey?.trim() || provider;
|
||||
const statusLabel = reference.statusLabel ?? externalObjectCategoryLabel(reference.statusCategory);
|
||||
const statusLabel = externalObjectDisplayStatusLabel(reference);
|
||||
const livenessLabel = externalObjectLivenessLabel(reference.liveness);
|
||||
const livenessSuffix = reference.liveness === "fresh" || reference.liveness === "unknown"
|
||||
|| livenessLabel.toLowerCase() === statusLabel.toLowerCase()
|
||||
? ""
|
||||
: ` (${livenessLabel})`;
|
||||
const titleParts = [
|
||||
@@ -786,6 +789,7 @@ function MarkdownBodyImpl({
|
||||
resolveWikiLinkHref,
|
||||
externalReferences,
|
||||
resolveImageSrc,
|
||||
resolveLinkHref,
|
||||
onImageClick,
|
||||
mediaMode = "render",
|
||||
resolveWorkspaceFileRef,
|
||||
@@ -967,6 +971,14 @@ function MarkdownBodyImpl({
|
||||
);
|
||||
}
|
||||
|
||||
const resolvedHref = href && resolveLinkHref ? resolveLinkHref(href) : href;
|
||||
if (resolveLinkHref && resolvedHref !== href) {
|
||||
return resolvedHref ? (
|
||||
<Link to={resolvedHref} style={mergeWrapStyle(linkStyle as React.CSSProperties | undefined)}>
|
||||
{linkChildren}
|
||||
</Link>
|
||||
) : <>{linkChildren}</>;
|
||||
}
|
||||
const isGitHubLink = isGitHubUrl(href);
|
||||
const isExternal = isExternalHttpUrl(href);
|
||||
const leadingIcon = isGitHubLink ? (
|
||||
@@ -1010,7 +1022,7 @@ function MarkdownBodyImpl({
|
||||
};
|
||||
}
|
||||
return map;
|
||||
}, [theme, linkIssueReferences, linkCaseReferences, externalReferenceLookup, resolveImageSrc, onImageClick, mediaMode]);
|
||||
}, [theme, linkIssueReferences, linkCaseReferences, externalReferenceLookup, resolveImageSrc, resolveLinkHref, onImageClick, mediaMode]);
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -931,6 +931,17 @@ describe("MarkdownEditor", () => {
|
||||
expect(mdxEditorMockState.insertedMarkdownValues).toEqual([pasted]);
|
||||
expect(innerPaste).not.toHaveBeenCalled();
|
||||
|
||||
const dashed = new Event("paste", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(dashed, "clipboardData", {
|
||||
value: { types: ["text/plain"], getData: () => "- a single dashed line" },
|
||||
});
|
||||
await act(async () => { editable.dispatchEvent(dashed); });
|
||||
expect(dashed.defaultPrevented).toBe(true);
|
||||
expect(mdxEditorMockState.insertedMarkdownValues).toEqual([
|
||||
pasted,
|
||||
"- a single dashed line",
|
||||
]);
|
||||
|
||||
const plain = new Event("paste", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(plain, "clipboardData", {
|
||||
value: { types: ["text/plain"], getData: () => "ordinary text" },
|
||||
@@ -941,6 +952,54 @@ describe("MarkdownEditor", () => {
|
||||
await act(async () => { root.unmount(); });
|
||||
});
|
||||
|
||||
it("leaves a markdown paste inside a nested code block", async () => {
|
||||
const root = createRoot(container);
|
||||
await act(async () => {
|
||||
root.render(<MarkdownEditor value="```txt\n\n```" onChange={() => {}} />);
|
||||
});
|
||||
await flush();
|
||||
|
||||
const editable = container.querySelector('[data-testid="mdx-editor"]') as HTMLDivElement;
|
||||
const code = document.createElement("div");
|
||||
code.className = "cm-content";
|
||||
code.setAttribute("contenteditable", "true");
|
||||
const text = document.createTextNode("");
|
||||
code.appendChild(text);
|
||||
editable.appendChild(code);
|
||||
|
||||
const range = document.createRange();
|
||||
range.setStart(text, 0);
|
||||
range.collapse(true);
|
||||
const selection = window.getSelection();
|
||||
selection?.removeAllRanges();
|
||||
selection?.addRange(range);
|
||||
code.focus();
|
||||
|
||||
const pasted = "- keep this line in the code block\n- and this one";
|
||||
const event = new Event("paste", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(event, "clipboardData", {
|
||||
configurable: true,
|
||||
value: {
|
||||
types: ["text/plain"],
|
||||
getData: (type: string) => (type === "text/plain" ? pasted : ""),
|
||||
},
|
||||
});
|
||||
const innerPaste = vi.fn();
|
||||
code.addEventListener("paste", innerPaste);
|
||||
|
||||
await act(async () => {
|
||||
code.dispatchEvent(event);
|
||||
});
|
||||
|
||||
expect(event.defaultPrevented).toBe(false);
|
||||
expect(mdxEditorMockState.insertedMarkdownValues).toEqual([]);
|
||||
expect(innerPaste).toHaveBeenCalledOnce();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("escapes angle brackets in pasted markdown", async () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
|
||||
@@ -510,12 +510,22 @@ function getMentionMenuSize(optionCount: number): MentionMenuSize {
|
||||
};
|
||||
}
|
||||
|
||||
// CodeMirror's editable surface is `.cm-content`, not a `pre` or `code` node.
|
||||
// MDXEditor wraps that surface in a hashed `codeMirrorWrapper` class. A paste
|
||||
// that starts inside either of those belongs to the nested editor.
|
||||
const CODE_LIKE_SELECTOR = [
|
||||
"pre",
|
||||
"code",
|
||||
".cm-editor",
|
||||
".cm-content",
|
||||
"[class*='codeMirrorWrapper']",
|
||||
"[class*='codeBlockEditor']",
|
||||
].join(",");
|
||||
|
||||
function nodeInsideCodeLike(container: HTMLElement, node: Node | null): boolean {
|
||||
if (!node || !container.contains(node)) return false;
|
||||
const el = node.nodeType === Node.ELEMENT_NODE
|
||||
? (node as HTMLElement)
|
||||
: node.parentElement;
|
||||
return Boolean(el?.closest("pre, code"));
|
||||
const el = node instanceof Element ? node : node.parentElement;
|
||||
return Boolean(el?.closest(CODE_LIKE_SELECTOR));
|
||||
}
|
||||
|
||||
function isSelectionInsideCodeLikeElement(container: HTMLElement | null) {
|
||||
@@ -528,6 +538,17 @@ function isSelectionInsideCodeLikeElement(container: HTMLElement | null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
function isPasteInsideCodeLikeElement(
|
||||
container: HTMLElement | null,
|
||||
event: { target: EventTarget | null },
|
||||
): boolean {
|
||||
if (!container) return false;
|
||||
if (event.target instanceof Node && nodeInsideCodeLike(container, event.target)) return true;
|
||||
const active = typeof document !== "undefined" ? document.activeElement : null;
|
||||
if (active instanceof Node && nodeInsideCodeLike(container, active)) return true;
|
||||
return isSelectionInsideCodeLikeElement(container);
|
||||
}
|
||||
|
||||
/** The human title of an issue mention — `name` minus its leading identifier. */
|
||||
export function issueMentionTitle(option: MentionOption): string {
|
||||
const name = option.name.trim();
|
||||
@@ -1280,7 +1301,7 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
|
||||
if (!clipboard || !ref.current) return;
|
||||
const types = new Set(Array.from(clipboard.types));
|
||||
if (types.has("Files") || types.has("text/html")) return;
|
||||
if (isSelectionInsideCodeLikeElement(containerRef.current)) return;
|
||||
if (isPasteInsideCodeLikeElement(containerRef.current, event)) return;
|
||||
|
||||
const rawText = clipboard.getData("text/plain");
|
||||
if (!looksLikeMarkdownPaste(rawText)) return;
|
||||
|
||||
@@ -91,4 +91,57 @@ describe("MarkdownBody external object decoration", () => {
|
||||
});
|
||||
expect(html).toContain('aria-label="HubSpot Reconnect (Requires auth): Acme deal"');
|
||||
});
|
||||
|
||||
it("labels detected-but-unresolved GitHub objects as not yet refreshed, not not yet resolved", () => {
|
||||
const html = render("See https://github.com/acme/web/pull/241", {
|
||||
"https://github.com/acme/web/pull/241": {
|
||||
providerKey: "github",
|
||||
objectType: "pull_request",
|
||||
displayKey: "Github Pull Request",
|
||||
iconKey: "github",
|
||||
statusCategory: "unknown",
|
||||
liveness: "unknown",
|
||||
statusLabel: null,
|
||||
displayTitle: "acme/web#241",
|
||||
},
|
||||
});
|
||||
expect(html).toContain("data-external-link=\"resolved\"");
|
||||
expect(html).toContain('aria-label="Github Pull Request Not yet refreshed: acme/web#241"');
|
||||
expect(html).not.toContain("Not yet resolved");
|
||||
});
|
||||
|
||||
it("does not repeat the liveness label when the status label equals it", () => {
|
||||
const html = render("Auth-blocked: https://github.com/acme/web/pull/241", {
|
||||
"https://github.com/acme/web/pull/241": {
|
||||
providerKey: "github",
|
||||
objectType: "pull_request",
|
||||
displayKey: "Github Pull Request",
|
||||
iconKey: "github",
|
||||
statusCategory: "unknown",
|
||||
liveness: "auth_required",
|
||||
statusLabel: null,
|
||||
displayTitle: "acme/web#241",
|
||||
},
|
||||
});
|
||||
expect(html).toContain('aria-label="Github Pull Request Requires auth: acme/web#241"');
|
||||
expect(html).not.toContain("Requires auth (Requires auth)");
|
||||
expect(html).not.toContain("(Requires auth)");
|
||||
});
|
||||
|
||||
it("does not repeat the liveness label when the status label equals it for unreachable", () => {
|
||||
const html = render("Down: https://github.com/acme/web/pull/241", {
|
||||
"https://github.com/acme/web/pull/241": {
|
||||
providerKey: "github",
|
||||
objectType: "pull_request",
|
||||
displayKey: "Github Pull Request",
|
||||
iconKey: "github",
|
||||
statusCategory: "unknown",
|
||||
liveness: "unreachable",
|
||||
statusLabel: null,
|
||||
displayTitle: "acme/web#241",
|
||||
},
|
||||
});
|
||||
expect(html).toContain('aria-label="Github Pull Request Unreachable: acme/web#241"');
|
||||
expect(html).not.toContain("(Unreachable)");
|
||||
});
|
||||
});
|
||||
@@ -273,6 +273,16 @@ async function flushReact() {
|
||||
});
|
||||
}
|
||||
|
||||
function renderWizardView(root: ReturnType<typeof createRoot>, queryClient: QueryClient) {
|
||||
return act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const SESSION_USER_ID = "user-b";
|
||||
|
||||
function render() {
|
||||
@@ -422,13 +432,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
mockAdapterRegistry.list = [{ type: "claude_local" }, { type: "codex_local" }];
|
||||
const { root, queryClient } = render();
|
||||
const renderTree = () =>
|
||||
act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
renderWizardView(root, queryClient);
|
||||
await renderTree();
|
||||
await flushReact();
|
||||
return { root, renderTree };
|
||||
@@ -516,13 +520,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
]);
|
||||
mockAdapterRegistry.list = [{ type: "claude_local" }, { type: "codex_local" }];
|
||||
const { root, queryClient } = render();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
const clickText = async (match: (t: string) => boolean) => {
|
||||
@@ -592,13 +590,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
mockAdapterRegistry.list = [{ type: "claude_local" }, { type: "codex_local" }];
|
||||
const { root, queryClient } = render();
|
||||
const renderTree = () =>
|
||||
act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
renderWizardView(root, queryClient);
|
||||
await renderTree();
|
||||
await flushReact();
|
||||
|
||||
@@ -772,13 +764,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
mockCompaniesApi.list.mockResolvedValue([]);
|
||||
|
||||
const { root, queryClient } = render();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
const clickByText = async (match: (text: string) => boolean) => {
|
||||
@@ -842,6 +828,8 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
"No stored Claude login was found for this agent.",
|
||||
);
|
||||
|
||||
expect(document.body.textContent).toContain("No working authentication was found");
|
||||
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
|
||||
@@ -1240,31 +1228,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
|
||||
it("blocks the hire when the probe reports warn with adapter_auth_missing and no stored login exists", async () => {
|
||||
// The default `beforeEach` mock already rejects with a 404 `ApiError`.
|
||||
mockAgentsApi.testEnvironment.mockResolvedValue({
|
||||
adapterType: "claude_local",
|
||||
status: "warn" as const,
|
||||
checks: [
|
||||
{
|
||||
code: ADAPTER_AUTH_MISSING_CHECK_CODE,
|
||||
level: "warn" as const,
|
||||
message: "No stored Claude login was found for this agent.",
|
||||
},
|
||||
],
|
||||
testedAt: new Date().toISOString(),
|
||||
});
|
||||
const { root, clickByText } = await openConnectStep();
|
||||
|
||||
await clickByText((t) => isArcPrimary(t));
|
||||
|
||||
expect(mockAgentsApi.hire).not.toHaveBeenCalled();
|
||||
expect(document.body.textContent).toContain(
|
||||
"No working authentication was found",
|
||||
);
|
||||
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
;
|
||||
|
||||
it("reads the stored-login status once for each create attempt", async () => {
|
||||
mockAgentsApi.getClaudeOAuthTokenStatus.mockReset();
|
||||
@@ -1321,13 +1285,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
|
||||
const { container, root, queryClient } = render();
|
||||
const renderTree = () =>
|
||||
act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
renderWizardView(root, queryClient);
|
||||
|
||||
await renderTree();
|
||||
await flushReact();
|
||||
@@ -1394,13 +1352,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
});
|
||||
|
||||
const { root, queryClient } = render();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
const companyNameInput = document.querySelector("input") as HTMLInputElement;
|
||||
@@ -1451,13 +1403,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
);
|
||||
|
||||
const { root, queryClient } = render();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
expect(document.querySelector("#onboarding-agent-name")).toBeNull();
|
||||
@@ -1513,13 +1459,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
]);
|
||||
|
||||
const { root, queryClient } = render();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
// Falls back to the wizard's default first step, not the stale step 4
|
||||
@@ -1553,13 +1493,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
mockCompaniesApi.list.mockRejectedValue(new Error("company list unavailable"));
|
||||
|
||||
const { root, queryClient } = render();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
// It mounts: the companies query sets `retry: false`, and with no
|
||||
@@ -1598,13 +1532,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
mockCompany.loading = false;
|
||||
|
||||
const { root, queryClient } = render();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
expect(localStorage).toHaveBeenCalled();
|
||||
@@ -1641,13 +1569,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
mockCompaniesApi.list.mockRejectedValue(new Error("refetch failed"));
|
||||
|
||||
const { root, queryClient } = render();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
// Mounted rather than blank...
|
||||
@@ -1689,13 +1611,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
mockCompaniesApi.list.mockRejectedValue(new Error("company list unavailable"));
|
||||
|
||||
const { root, queryClient } = render();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
expect(window.localStorage.getItem(ONBOARDING_STORAGE_KEY)).toBe(draft);
|
||||
@@ -1733,13 +1649,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
mockCompaniesApi.list.mockRejectedValue(new Error("refetch failed for the new account"));
|
||||
|
||||
const { root, queryClient } = render();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
// Account A's agent name must not appear in account B's wizard.
|
||||
@@ -1787,13 +1697,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
]);
|
||||
|
||||
const { root, queryClient } = render();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
// Mounted — so this is a real observation, not an unmounted false pass.
|
||||
@@ -1823,13 +1727,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
);
|
||||
|
||||
const { root, queryClient } = render();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
expect(window.localStorage.getItem(ONBOARDING_STORAGE_KEY)).not.toBeNull();
|
||||
@@ -1861,13 +1759,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
// B's session: the refetch fails, so A's data is retained.
|
||||
mockCompaniesApi.list.mockRejectedValue(new Error("refetch failed"));
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
// Mounted, so this observes the real thing rather than an empty document.
|
||||
@@ -1903,13 +1795,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
});
|
||||
mockCompaniesApi.list.mockReturnValue(new Promise(() => {}));
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
// Nothing mounted, so nothing could have written over the draft.
|
||||
@@ -1927,13 +1813,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
const { root, queryClient } = render();
|
||||
mockCompaniesApi.list.mockReturnValue(new Promise(() => {}));
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
await flushReact();
|
||||
|
||||
expect(window.localStorage.getItem(ONBOARDING_STORAGE_KEY)).toBeNull();
|
||||
@@ -2002,13 +1882,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
mockDialog.onboardingOptions = {};
|
||||
|
||||
const { root, queryClient } = render();
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OnboardingWizard />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
await renderWizardView(root, queryClient);
|
||||
// The login-panel gate chains several dependent queries (environments,
|
||||
// instance settings, environment capabilities, then the auth signal
|
||||
// itself), each settling on its own render. One flush is not always
|
||||
@@ -3052,6 +2926,8 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
|
||||
it("renders no 'Use saved login' control", async () => {
|
||||
mockAgentsApi.getAdapterAuthSignal.mockResolvedValue({ status: "absent" });
|
||||
const { root } = await openStep4({ adapterType: "claude_local" });
|
||||
await pickSource(/Claude/);
|
||||
expect(document.body.textContent).toContain("Sign in to Claude then come back and enter authorization code");
|
||||
expect(document.body.textContent).not.toContain("Use saved login");
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
|
||||
@@ -21,7 +21,7 @@ function truncatePath(path: string) {
|
||||
}
|
||||
|
||||
interface ProjectWorkspaceSummaryCardProps {
|
||||
projectRef: string;
|
||||
projectRef: string | null;
|
||||
summary: ProjectWorkspaceSummary;
|
||||
runtimeActionKey: string | null;
|
||||
runtimeActionPending: boolean;
|
||||
@@ -50,7 +50,7 @@ export function ProjectWorkspaceSummaryCard({
|
||||
const visibleIssues = summary.issues.slice(0, 4);
|
||||
const hiddenIssueCount = Math.max(summary.linkedIssueCount - visibleIssues.length, 0);
|
||||
const workspaceHref =
|
||||
summary.kind === "project_workspace"
|
||||
summary.kind === "project_workspace" && projectRef
|
||||
? projectWorkspaceUrl({ id: projectRef, urlKey: projectRef }, summary.workspaceId)
|
||||
: `/execution-workspaces/${summary.workspaceId}`;
|
||||
const hasRunningServices = summary.runningServiceCount > 0;
|
||||
|
||||
@@ -15,8 +15,8 @@ export function ProjectWorkspacesContent({
|
||||
summaries,
|
||||
}: {
|
||||
companyId: string;
|
||||
projectId: string;
|
||||
projectRef: string;
|
||||
projectId: string | null;
|
||||
projectRef: string | null;
|
||||
summaries: ProjectWorkspaceSummary[];
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
@@ -35,6 +35,7 @@ export function ProjectWorkspacesContent({
|
||||
}) => {
|
||||
setRuntimeActionKey(`${input.key}:${input.action}`);
|
||||
if (input.kind === "project_workspace") {
|
||||
if (!projectId) throw new Error("Project workspace has no project");
|
||||
return await projectsApi.controlWorkspaceRuntimeServices(projectId, input.workspaceId, input.action, companyId);
|
||||
}
|
||||
return await executionWorkspacesApi.controlRuntimeServices(input.workspaceId, input.action);
|
||||
@@ -43,11 +44,11 @@ export function ProjectWorkspacesContent({
|
||||
setRuntimeActionKey(null);
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.executionWorkspaces.overview(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.executionWorkspaces.list(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.executionWorkspaces.list(companyId, { projectId }) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.projects.detail(projectId) });
|
||||
if (projectId) queryClient.invalidateQueries({ queryKey: queryKeys.executionWorkspaces.list(companyId, { projectId }) });
|
||||
if (projectId) queryClient.invalidateQueries({ queryKey: queryKeys.projects.detail(projectId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.projects.all(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.listByProject(companyId, projectId) });
|
||||
if (projectId) queryClient.invalidateQueries({ queryKey: queryKeys.issues.listByProject(companyId, projectId) });
|
||||
},
|
||||
});
|
||||
|
||||
@@ -107,11 +108,11 @@ export function ProjectWorkspacesContent({
|
||||
onClosed={() => {
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.executionWorkspaces.overview(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.executionWorkspaces.list(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.executionWorkspaces.list(companyId, { projectId }) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.projects.detail(projectId) });
|
||||
if (projectId) queryClient.invalidateQueries({ queryKey: queryKeys.executionWorkspaces.list(companyId, { projectId }) });
|
||||
if (projectId) queryClient.invalidateQueries({ queryKey: queryKeys.projects.detail(projectId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.projects.all(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.listByProject(companyId, projectId) });
|
||||
if (projectId) queryClient.invalidateQueries({ queryKey: queryKeys.issues.listByProject(companyId, projectId) });
|
||||
setClosingWorkspace(null);
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { ProviderQuotaCard } from "./ProviderQuotaCard";
|
||||
import { BillerSpendCard } from "./BillerSpendCard";
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const base = { provider: "openai", biller: "openai", billingType: "metered_api" as const, model: "gpt-6-astra",
|
||||
inputTokens: 10, cachedInputTokens: 0, outputTokens: 2, apiRunCount: 1, subscriptionRunCount: 0,
|
||||
subscriptionInputTokens: 0, subscriptionCachedInputTokens: 0, subscriptionOutputTokens: 0,
|
||||
providerCount: 1, modelCount: 1 };
|
||||
const cases = [
|
||||
{ name: "unpriced", costCents: 0, eventCount: 2, estimatedEventCount: 0, unpricedEventCount: 2, amount: "—", estimate: null, unavailable: "2 costs unavailable" },
|
||||
{ name: "mixed", costCents: 125, eventCount: 3, estimatedEventCount: 1, unpricedEventCount: 1, amount: "$1.25", estimate: "Partially estimated", unavailable: "1 cost unavailable" },
|
||||
{ name: "estimated", costCents: 125, eventCount: 2, estimatedEventCount: 2, unpricedEventCount: 0, amount: "$1.25", estimate: "Estimated", unavailable: null },
|
||||
{ name: "included subscription", costCents: 0, eventCount: 2, estimatedEventCount: 0, unpricedEventCount: 0, amount: "$0.00", estimate: null, unavailable: null },
|
||||
{ name: "older response", costCents: 125, amount: "$1.25", estimate: null, unavailable: null },
|
||||
];
|
||||
describe.each(["provider", "biller"] as const)("%s price status", kind => {
|
||||
let container: HTMLDivElement, root: ReturnType<typeof createRoot>;
|
||||
beforeEach(() => { container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); });
|
||||
afterEach(() => { act(() => root.unmount()); container.remove(); });
|
||||
it.each(cases)("labels $name totals without implying missing costs are free", async example => {
|
||||
const row = { ...base, ...example };
|
||||
const props = { budgetMonthlyCents: 0, totalCompanySpendCents: row.costCents, weekSpendCents: 0 };
|
||||
await act(async () => root.render(kind === "provider"
|
||||
? <ProviderQuotaCard {...props} provider="openai" rows={[row]} windowRows={[]} showDeficitNotch={false} />
|
||||
: <BillerSpendCard {...props} row={row} providerRows={[row]} />));
|
||||
const header = container.querySelector('[data-slot="card-header"]')!;
|
||||
expect(header.textContent).toContain(example.amount);
|
||||
if (example.amount === "—") expect(header.textContent).not.toContain("$0.00");
|
||||
const badges = [...header.querySelectorAll('[data-slot="badge"]')].map(badge => badge.textContent);
|
||||
expect(badges).toEqual([example.estimate, example.unavailable].filter(Boolean));
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import type { CostByProviderModel, CostWindowSpendRow, QuotaWindow, ProviderQuot
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { QuotaBar } from "./QuotaBar";
|
||||
import { CostAmount } from "./CostAmount";
|
||||
import { ClaudeSubscriptionPanel } from "./ClaudeSubscriptionPanel";
|
||||
import { CodexSubscriptionPanel } from "./CodexSubscriptionPanel";
|
||||
import {
|
||||
@@ -63,10 +64,14 @@ export function ProviderQuotaCard({
|
||||
const totals = useMemo(() => {
|
||||
let inputTokens = 0, outputTokens = 0, costCents = 0;
|
||||
let apiRunCount = 0, subRunCount = 0, subInputTokens = 0, subOutputTokens = 0;
|
||||
let eventCount = 0, estimatedEventCount = 0, unpricedEventCount = 0;
|
||||
for (const r of rows) {
|
||||
inputTokens += r.inputTokens + r.cachedInputTokens;
|
||||
outputTokens += r.outputTokens;
|
||||
costCents += r.costCents;
|
||||
eventCount += r.eventCount ?? 0;
|
||||
estimatedEventCount += r.estimatedEventCount ?? 0;
|
||||
unpricedEventCount += r.unpricedEventCount ?? 0;
|
||||
apiRunCount += r.apiRunCount;
|
||||
subRunCount += r.subscriptionRunCount;
|
||||
subInputTokens += r.subscriptionInputTokens + r.subscriptionCachedInputTokens;
|
||||
@@ -81,6 +86,7 @@ export function ProviderQuotaCard({
|
||||
totalOutputTokens: outputTokens,
|
||||
totalTokens,
|
||||
totalCostCents: costCents,
|
||||
eventCount, estimatedEventCount, unpricedEventCount,
|
||||
totalApiRuns: apiRunCount,
|
||||
totalSubRuns: subRunCount,
|
||||
totalSubInputTokens: subInputTokens,
|
||||
@@ -156,9 +162,10 @@ export function ProviderQuotaCard({
|
||||
)}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<span className="text-xl font-bold tabular-nums shrink-0">
|
||||
{formatCents(totalCostCents)}
|
||||
</span>
|
||||
<div className="text-xl shrink-0">
|
||||
<CostAmount costCents={totalCostCents} eventCount={totals.eventCount}
|
||||
estimatedEventCount={totals.estimatedEventCount} unpricedEventCount={totals.unpricedEventCount} showUnavailableCount />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { RoutineSectionHeading } from "./RoutineSectionHeading";
|
||||
|
||||
const copyTextToClipboard = vi.hoisted(() => vi.fn(async () => {}));
|
||||
|
||||
vi.mock("@/lib/clipboard", () => ({
|
||||
copyTextToClipboard,
|
||||
}));
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
async function act(callback: () => void | Promise<void>) {
|
||||
let result: void | Promise<void> = undefined;
|
||||
flushSync(() => {
|
||||
result = callback();
|
||||
});
|
||||
await result;
|
||||
}
|
||||
|
||||
describe("RoutineSectionHeading", () => {
|
||||
let container: HTMLDivElement;
|
||||
|
||||
afterEach(() => {
|
||||
container?.remove();
|
||||
copyTextToClipboard.mockClear();
|
||||
});
|
||||
|
||||
it("copies the description markdown from the button next to the heading", async () => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const description = "```text\n- keep this line\n```";
|
||||
|
||||
await act(async () => {
|
||||
root.render(<RoutineSectionHeading title="Overview" copyText={description} />);
|
||||
});
|
||||
|
||||
const button = container.querySelector('button[aria-label="Copy description"]');
|
||||
expect(button).not.toBeNull();
|
||||
expect(container.querySelector("#routine-section-title")?.textContent).toBe("Overview");
|
||||
|
||||
await act(async () => {
|
||||
button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(copyTextToClipboard).toHaveBeenCalledWith(description);
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("omits the copy button on sections that are not the overview", async () => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root.render(<RoutineSectionHeading title="Triggers" />);
|
||||
});
|
||||
|
||||
expect(container.querySelector('button[aria-label="Copy description"]')).toBeNull();
|
||||
expect(container.querySelector("#routine-section-title")?.textContent).toBe("Triggers");
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Copy } from "lucide-react";
|
||||
import { CopyText } from "./CopyText";
|
||||
|
||||
export function RoutineSectionHeading({
|
||||
title,
|
||||
copyText = null,
|
||||
}: {
|
||||
title: string;
|
||||
/** Description markdown to copy. Omit the button when this is null. */
|
||||
copyText?: string | null;
|
||||
}) {
|
||||
return (
|
||||
<div className="mb-4 flex items-center gap-1">
|
||||
<h2 id="routine-section-title" className="text-lg font-semibold">
|
||||
{title}
|
||||
</h2>
|
||||
{copyText != null ? (
|
||||
<CopyText
|
||||
text={copyText}
|
||||
ariaLabel="Copy description"
|
||||
title="Copy description"
|
||||
copiedLabel="Description copied"
|
||||
className="inline-flex size-6 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
<Copy className="size-3.5" aria-hidden="true" />
|
||||
</CopyText>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { expect, it } from "vitest";
|
||||
import { RuntimeTestCard } from "./RuntimeTestCard";
|
||||
|
||||
it("shows the installation repair directly on a missing runtime test", () => {
|
||||
const container = document.createElement("div");
|
||||
const root = createRoot(container);
|
||||
const message = "The ACPX claude runtime is incomplete: required package @agentclientprotocol/claude-agent-acp is missing. Reinstall or rebuild Paperclip with its bundled provider dependencies, restart the server, then test the agent's runtime before retrying.";
|
||||
try {
|
||||
flushSync(() => root.render(<RuntimeTestCard state="fail" onTest={() => {}} result={{
|
||||
adapterType: "paperclip_runner", status: "fail", testedAt: "2026-10-11T11:19:14Z",
|
||||
checks: [{ code: "acpx_runtime_package_missing", level: "error", message }],
|
||||
}} />));
|
||||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("Runtime missing");
|
||||
expect(container.querySelector('[role="alert"]')?.textContent).toContain(message);
|
||||
expect(container.textContent).not.toContain("Check your model and provider connection");
|
||||
} finally {
|
||||
flushSync(() => root.unmount());
|
||||
}
|
||||
});
|
||||
@@ -61,7 +61,12 @@ export function RuntimeTestCard({
|
||||
disabled?: boolean;
|
||||
variant?: "connection" | "prerequisites";
|
||||
}) {
|
||||
const content = (variant === "prerequisites" ? prerequisiteCopy : copy)[state];
|
||||
const missingRuntime = state === "fail"
|
||||
? result?.checks.find(check => check.code === "acpx_runtime_package_missing")
|
||||
: undefined;
|
||||
const content = missingRuntime
|
||||
? { ...copy.fail, title: "Runtime missing", description: missingRuntime.message }
|
||||
: (variant === "prerequisites" ? prerequisiteCopy : copy)[state];
|
||||
const Icon =
|
||||
state === "running"
|
||||
? Loader2
|
||||
|
||||
@@ -4658,3 +4658,16 @@ describe("TaskChatThread composer execution controls", () => {
|
||||
expect(container.querySelector('[data-testid="task-chat-composer-stop"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("explains a missing provider runtime with an installation repair", () => {
|
||||
render(<TaskChatThread comments={[]} onAdd={async () => {}} linkedRuns={[{
|
||||
runId: "missing-runtime", runtimeMode: "native", status: "failed", errorCode: "native_provider_runtime_missing",
|
||||
agentId: "agent-1", agentName: "Content Strategist", adapterType: "paperclip_runner",
|
||||
createdAt: "2026-10-11T11:19:08Z", startedAt: "2026-10-11T11:19:08Z", finishedAt: "2026-10-11T11:19:14Z",
|
||||
}]} />);
|
||||
expect(container.textContent).toContain("Runtime missing");
|
||||
const toggle = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-collapsible-marker"] button[aria-expanded]')!;
|
||||
flushSync(() => toggle.click());
|
||||
expect(container.textContent).toContain("Reinstall or rebuild Paperclip");
|
||||
expect(container.textContent).toContain("test the agent's runtime");
|
||||
});
|
||||
@@ -527,6 +527,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
|
||||
conversationMode,
|
||||
reassignOptions,
|
||||
currentAssigneeValue,
|
||||
suggestedAssigneeValue,
|
||||
assigneeAdapterOverrides,
|
||||
issueStatus,
|
||||
issueAssigneeAgentId = null,
|
||||
@@ -604,12 +605,15 @@ export function TaskChatThread(props: TaskChatThreadProps) {
|
||||
const [pendingComposerAssignee, setPendingComposerAssignee] = useState<
|
||||
string | null
|
||||
>(null);
|
||||
const effectiveGoalAgentId =
|
||||
pendingComposerAssignee === null
|
||||
? issueAssigneeAgentId
|
||||
: pendingComposerAssignee.startsWith("agent:")
|
||||
? pendingComposerAssignee.slice("agent:".length) || null
|
||||
: null;
|
||||
const composerSuggestedAssignee = currentUserId && currentAssigneeValue === `user:${currentUserId}`
|
||||
? suggestedAssigneeValue
|
||||
: undefined;
|
||||
const effectiveComposerAssignee = pendingComposerAssignee ?? composerSuggestedAssignee;
|
||||
const effectiveGoalAgentId = effectiveComposerAssignee === undefined
|
||||
? issueAssigneeAgentId
|
||||
: effectiveComposerAssignee.startsWith("agent:")
|
||||
? effectiveComposerAssignee.slice("agent:".length) || null
|
||||
: null;
|
||||
const runnerGoal = useRunnerGoalControl(issueId, effectiveGoalAgentId);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -1646,7 +1650,9 @@ export function TaskChatThread(props: TaskChatThreadProps) {
|
||||
? "native_runner_timed_out"
|
||||
: "native_runner_process_exited");
|
||||
const label =
|
||||
code === "native_provider_model_rejected" && source.status === "failed"
|
||||
code === "native_provider_runtime_missing" && source.status === "failed"
|
||||
? "Runtime missing"
|
||||
: code === "native_provider_model_rejected" && source.status === "failed"
|
||||
? "Model unavailable"
|
||||
: code === "native_provider_approval_required" && source.status === "failed"
|
||||
? "Approval required"
|
||||
@@ -1667,6 +1673,8 @@ export function TaskChatThread(props: TaskChatThreadProps) {
|
||||
? `The run was cancelled${responseBoundary}.`
|
||||
: source.status === "interrupted"
|
||||
? `The run was interrupted${responseBoundary}.`
|
||||
: code === "native_provider_runtime_missing"
|
||||
? "The selected provider runtime is missing a required package. Reinstall or rebuild Paperclip with its bundled provider dependencies, restart the server, then test the agent's runtime before retrying."
|
||||
: code === "native_provider_approval_required"
|
||||
? "This operation requires approval, but this runner has no interactive approval handler. Review the operation and update the agent's permission setting before retrying."
|
||||
: code === "native_provider_model_rejected"
|
||||
@@ -2656,6 +2664,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
|
||||
return (
|
||||
<TaskChatBubbleActions
|
||||
copyText={item.text}
|
||||
fastResponse={item.origin === "fast_response"}
|
||||
feedback={
|
||||
onVote
|
||||
? {
|
||||
@@ -3235,6 +3244,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
|
||||
modelAgents={agentMap}
|
||||
userProfileMap={userProfileMap}
|
||||
currentAssigneeValue={currentAssigneeValue}
|
||||
suggestedAssigneeValue={composerSuggestedAssignee}
|
||||
companyId={companyId}
|
||||
assigneeAdapterOverrides={assigneeAdapterOverrides}
|
||||
onPendingAssigneeChange={setPendingComposerAssignee}
|
||||
|
||||
@@ -1,72 +1,44 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import type { IssueRecoveryAction } from "@paperclipai/shared";
|
||||
import { WorkspaceExportRecovery } from "./WorkspaceExportRecovery";
|
||||
const retry = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../api/issues", () => ({ issuesApi: { retryWorkspaceExport: retry } }));
|
||||
const action = { id: "action", cause: "native_workspace_sync_out_retry_exhausted", status: "active", updatedAt: "2026-01-01T00:00:00Z", ownerType: "board", evidence: { runId: "run" }, wakePolicy: null } as unknown as IssueRecoveryAction;
|
||||
const action = { cause: "native_workspace_finalization_owner_unverified", status: "escalated", ownerType: "board", evidence: { runId: "run", owner: { token: "owner", hostname: "secret-host", pid: 2 } }, wakePolicy: null } as unknown as IssueRecoveryAction;
|
||||
describe("WorkspaceExportRecovery", () => {
|
||||
let root: Root, container: HTMLDivElement, client: QueryClient;
|
||||
const onQueued = vi.fn();
|
||||
beforeEach(() => {
|
||||
retry.mockReset().mockResolvedValue({ status: "queued" }); onQueued.mockReset();
|
||||
container = document.createElement("div"); document.body.append(container); root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
|
||||
});
|
||||
afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); });
|
||||
async function mount(overrides: Partial<Parameters<typeof WorkspaceExportRecovery>[0]> = {}) {
|
||||
await act(async () => root.render(<QueryClientProvider client={client}><WorkspaceExportRecovery issueId="issue" action={action} canManage onQueued={onQueued} {...overrides} /></QueryClientProvider>));
|
||||
let root: Root, container: HTMLDivElement;
|
||||
beforeEach(() => { container = document.createElement("div"); document.body.append(container); root = createRoot(container); });
|
||||
afterEach(async () => { await act(async () => root.unmount()); container.remove(); });
|
||||
async function mount(value: IssueRecoveryAction | null) {
|
||||
await act(async () => root.render(<WorkspaceExportRecovery action={value} />));
|
||||
expect(container.querySelector("textarea, button, details, input")).toBeNull();
|
||||
expect(container.textContent).not.toContain("secret-host");
|
||||
}
|
||||
async function enterNote() {
|
||||
const textarea = container.querySelector("textarea")!;
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(textarea, "Restored provider connectivity while preserving all saved files.");
|
||||
textarea.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
}
|
||||
async function submit() {
|
||||
await act(async () => container.querySelector("button")!.click());
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
|
||||
}
|
||||
it("requires a repair note and submits only the exact recorded run", async () => {
|
||||
await mount(); expect(container.querySelector("button")!.disabled).toBe(true);
|
||||
await enterNote(); await submit();
|
||||
expect(retry).toHaveBeenCalledWith("issue", { actionId: "action", runId: "run", repairNote: "Restored provider connectivity while preserving all saved files." });
|
||||
expect(onQueued).toHaveBeenCalledOnce();
|
||||
expect(container.querySelector('[role="status"]')?.textContent).toContain("agent will not repeat its work");
|
||||
it("shows a quiet status while the harness restores work", async () => {
|
||||
await mount({ ...action, evidence: { ...action.evidence, workspaceOwnerRecovery: { state: "resuming" } } });
|
||||
expect(container.querySelector('[role="status"]')?.textContent).toBe("Restoring saved work…");
|
||||
});
|
||||
it("offers repair again when a queued export publishes a new permanent failure", async () => {
|
||||
await mount(); await enterNote(); await submit();
|
||||
expect(container.querySelector("button")).toBeNull();
|
||||
await mount({ action: { ...action, updatedAt: "2026-01-01T00:01:00Z", wakePolicy: null } });
|
||||
expect(container.querySelector("button")?.textContent).toBe("Retry workspace export");
|
||||
it("does not mistake platform identity for confirmed recovery", async () => {
|
||||
await mount({ ...action, evidence: { ...action.evidence, owner: { ...(action.evidence.owner as object), worker: { provider: "railway", deploymentId: "old" } } } });
|
||||
expect(container.textContent).toContain("operator assistance");
|
||||
});
|
||||
it("keeps unavailable-sandbox errors actionable inline", async () => {
|
||||
retry.mockRejectedValueOnce(new Error("Resume the retained sandbox before retrying.")); await mount();
|
||||
await enterNote(); await submit();
|
||||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("Resume the retained sandbox");
|
||||
it("states that an operator is needed for legacy receipts", async () => {
|
||||
await mount(action);
|
||||
expect(container.textContent).toContain("Workspace recovery needs operator assistance");
|
||||
});
|
||||
it("does not offer the action without runtime access", async () => {
|
||||
await mount({ canManage: false }); expect(container.querySelector("button")).toBeNull();
|
||||
it("keeps export repair out of the task", async () => {
|
||||
const cause = "native_workspace_sync_out_retry_exhausted";
|
||||
await mount({ ...action, cause });
|
||||
expect(container.textContent).toContain("operator assistance");
|
||||
});
|
||||
it("offers saved-result export after transient retries are exhausted without claiming an unsafe link", async () => {
|
||||
await mount({ action: { ...action, cause: "native_workspace_sync_out_retry_exhausted" } });
|
||||
expect(container.querySelector("button")?.textContent).toBe("Retry workspace export");
|
||||
expect(container.textContent).toContain("export failure");
|
||||
expect(container.textContent).not.toContain("unsafe link");
|
||||
await enterNote(); await submit();
|
||||
expect(retry).toHaveBeenCalledWith("issue", expect.objectContaining({ runId: "run" }));
|
||||
it("removes the status when recovery resolves, including updates in place", async () => {
|
||||
await mount({ ...action, evidence: { ...action.evidence, workspaceOwnerStop: {} } });
|
||||
expect(container.textContent).toBe("Restoring saved work…");
|
||||
await mount({ ...action, status: "resolved" }); expect(container.textContent).toBe("");
|
||||
await mount(null); expect(container.textContent).toBe("");
|
||||
});
|
||||
it("never asks users to repair historical unsafe exports", async () => {
|
||||
await mount({ action: { ...action, cause: "native_workspace_sync_out_unsafe_archive" } });
|
||||
expect(container.textContent).toBe("");
|
||||
expect(retry).not.toHaveBeenCalled();
|
||||
});
|
||||
it("does not offer a second retry while the same export is queued", async () => {
|
||||
await mount({ action: { ...action, wakePolicy: { kind: "resume_native_run" } } });
|
||||
expect(container.querySelector('[role="status"]')?.textContent).toContain("Export is queued"); expect(container.querySelector("button")).toBeNull();
|
||||
it("does not show unrelated or historical unsafe-export notices", async () => {
|
||||
await mount({ ...action, cause: "no_live_path", evidence: {} }); expect(container.textContent).toBe("");
|
||||
await mount({ ...action, cause: "native_workspace_sync_out_unsafe_archive" }); expect(container.textContent).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -1,43 +1,17 @@
|
||||
import { useId, useState } from "react";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import type { IssueRecoveryAction } from "@paperclipai/shared";
|
||||
import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared";
|
||||
import { issuesApi } from "../api/issues";
|
||||
import { Button } from "./ui/button";
|
||||
import { Label } from "./ui/label";
|
||||
import { Textarea } from "./ui/textarea";
|
||||
import { asObject, cn } from "../lib/utils";
|
||||
|
||||
/** Copyback repair preserves the accepted result and never wakes the provider. */
|
||||
export function WorkspaceExportRecovery({ issueId, action, canManage, onQueued }: {
|
||||
issueId: string; action: IssueRecoveryAction | null; canManage: boolean; onQueued: () => void;
|
||||
/** Infrastructure repair belongs to the harness/operator, never a task form. */
|
||||
export function WorkspaceExportRecovery({ action, className }: {
|
||||
className?: string; action: IssueRecoveryAction | null;
|
||||
}) {
|
||||
const noteId = useId();
|
||||
const [repairNote, setRepairNote] = useState("");
|
||||
const [queuedActionVersion, setQueuedActionVersion] = useState<string | null>(null);
|
||||
const retry = useMutation({
|
||||
mutationFn: () => issuesApi.retryWorkspaceExport(issueId, {
|
||||
actionId: action!.id, runId: action!.evidence.runId as string, repairNote: repairNote.trim(),
|
||||
}),
|
||||
onSuccess: () => { setQueuedActionVersion(String(action!.updatedAt)); onQueued(); },
|
||||
});
|
||||
if (!action || !isNativeWorkspaceExportRepairCause(action.cause) || action.ownerType !== "board"
|
||||
const ownerRecovery = action?.cause === "native_workspace_finalization_owner_unverified";
|
||||
if (!action || (!ownerRecovery && !isNativeWorkspaceExportRepairCause(action.cause)) || action.ownerType !== "board"
|
||||
|| !["active", "escalated"].includes(action.status) || typeof action.evidence.runId !== "string") return null;
|
||||
const queued = queuedActionVersion === String(action.updatedAt) || action.wakePolicy?.kind === "resume_native_run";
|
||||
return <section aria-label="Workspace export repair" className="flex flex-col gap-2 p-4 text-sm">
|
||||
<p className="font-medium">Workspace export needs repair</p>
|
||||
{queued ? <p role="status">Export is queued for the saved result. The agent will not repeat its work.</p> : <>
|
||||
<p className="text-muted-foreground">{"Automatic workspace export retries stopped. Inspect the export failure, restore provider or destination availability, and preserve the saved files in the retained sandbox. Retry export here when the cause is resolved."}</p>
|
||||
{canManage ? <>
|
||||
<Label htmlFor={noteId}>Repair performed</Label>
|
||||
<Textarea id={noteId} value={repairNote} onChange={event => setRepairNote(event.target.value)} maxLength={12_000}
|
||||
placeholder="Describe the repair and how the saved workspace files were preserved." disabled={retry.isPending} />
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={() => retry.mutate()} disabled={retry.isPending || repairNote.trim().length < 20}>
|
||||
{retry.isPending ? "Queueing export…" : "Retry workspace export"}
|
||||
</Button>
|
||||
</div>
|
||||
</> : <p className="text-muted-foreground">A board member with runtime access can retry this export after repair.</p>}
|
||||
{retry.isError && <p role="alert" className="text-destructive">{retry.error instanceof Error ? retry.error.message : "Could not queue export. Refresh the task and inspect its run."}</p>}
|
||||
</>}
|
||||
</section>;
|
||||
const queued = !!action.evidence.workspaceOwnerStop || action.wakePolicy?.kind === "resume_native_run";
|
||||
const automatic = queued || (ownerRecovery && asObject(action.evidence.workspaceOwnerRecovery).state === "resuming");
|
||||
return <p role="status" className={cn("text-sm text-muted-foreground", className)}>
|
||||
{automatic ? "Restoring saved work…" : "Workspace recovery needs operator assistance. The agent’s result is saved."}
|
||||
</p>;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ExecutionBlocker, Issue } from "@paperclipai/shared";
|
||||
import { WorkspaceFileRecovery } from "./WorkspaceFileRecovery";
|
||||
const resolve = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../api/issues", () => ({ issuesApi: { resolveRecoveryAction: resolve } }));
|
||||
const blocker = { recoveryActionId: "held-source", runId: "original-run", cause: "legacy_execution_requires_reconciliation",
|
||||
workspaceRepairRequired: true, canRecordWorkspaceRepair: true, canRetry: false, canContinue: false, nextAction: "Recover the original files." } as ExecutionBlocker;
|
||||
|
||||
describe("workspace file recovery", () => {
|
||||
let root: Root, container: HTMLDivElement, client: QueryClient;
|
||||
const onRecorded = vi.fn();
|
||||
beforeEach(() => {
|
||||
resolve.mockReset().mockResolvedValue({}); onRecorded.mockReset();
|
||||
container = document.createElement("div"); document.body.append(container); root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
|
||||
});
|
||||
afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); });
|
||||
async function mount(overrides: Partial<Parameters<typeof WorkspaceFileRecovery>[0]> = {}) {
|
||||
await act(async () => root.render(<QueryClientProvider client={client}><WorkspaceFileRecovery
|
||||
issueId="task" issueStatus="in_progress" blocker={blocker} canManage onRecorded={onRecorded} {...overrides} />
|
||||
</QueryClientProvider>));
|
||||
}
|
||||
async function enterEvidence() {
|
||||
const textarea = container.querySelector("textarea")!;
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(textarea,
|
||||
"Recovered and verified both repository patches in the linked backup artifact.");
|
||||
textarea.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
}
|
||||
async function confirm() { await act(async () => container.querySelector<HTMLButtonElement>('[role="checkbox"]')!.click()); }
|
||||
async function submit() {
|
||||
await act(async () => Array.from(container.querySelectorAll("button")).find(b => b.textContent === "Record file recovery")!.click());
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
|
||||
}
|
||||
it.each(["in_progress", "in_review", "done", "cancelled"] as Issue["status"][])("records verified source files without changing the %s task", async issueStatus => {
|
||||
await mount({ issueStatus });
|
||||
const button = Array.from(container.querySelectorAll("button")).find(b => b.textContent === "Record file recovery")!;
|
||||
expect(button.disabled).toBe(true); await enterEvidence(); expect(button.disabled).toBe(true);
|
||||
await confirm(); expect(button.disabled).toBe(false); await submit();
|
||||
expect(resolve).toHaveBeenCalledWith("task", expect.objectContaining({ actionId: "held-source", sourceIssueStatus: issueStatus,
|
||||
outcome: "restored", executionReconciliation: expect.objectContaining({ runId: "original-run", providerStopped: true,
|
||||
workspaceRepairEvidence: "Recovered and verified both repository patches in the linked backup artifact." }) }));
|
||||
expect(onRecorded).toHaveBeenCalledOnce();
|
||||
expect(container.querySelector('[role="status"]')?.textContent).toContain("task status is unchanged");
|
||||
});
|
||||
it("keeps the hold and entered evidence when the server rejects unverified shutdown", async () => {
|
||||
resolve.mockRejectedValueOnce(new Error("The original workspace has not confirmed that it stopped."));
|
||||
await mount(); await enterEvidence(); await confirm(); await submit();
|
||||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("not confirmed");
|
||||
expect(container.querySelector("textarea")?.value).toContain("both repository patches");
|
||||
expect(onRecorded).not.toHaveBeenCalled();
|
||||
});
|
||||
it("does not offer attestation without board runtime access", async () => {
|
||||
await mount({ canManage: false }); expect(container.querySelector("button")).toBeNull();
|
||||
expect(container.textContent).toContain("board member with runtime access"); expect(resolve).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([
|
||||
{ workspaceRepairRequired: false }, { canRecordWorkspaceRepair: false }, { cause: "native_workspace_sync_out_retry_exhausted" },
|
||||
{ recoveryActionId: null }, { runId: null },
|
||||
])("does not expose file-only repair for other or unbound holds: %j", async patch => {
|
||||
await mount({ blocker: { ...blocker, ...patch } }); expect(container.textContent).toBe("");
|
||||
expect(resolve).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useId, useState } from "react";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import type { ExecutionBlocker, Issue } from "@paperclipai/shared";
|
||||
import { issuesApi } from "../api/issues";
|
||||
import { Button } from "./ui/button";
|
||||
import { Checkbox } from "./ui/checkbox";
|
||||
import { Label } from "./ui/label";
|
||||
import { Textarea } from "./ui/textarea";
|
||||
|
||||
export function WorkspaceFileRecovery({ issueId, issueStatus, blocker, canManage, onRecorded }: {
|
||||
issueId: string;
|
||||
issueStatus: Issue["status"];
|
||||
blocker: ExecutionBlocker;
|
||||
canManage: boolean;
|
||||
onRecorded: () => void;
|
||||
}) {
|
||||
const noteId = useId();
|
||||
const confirmationId = useId();
|
||||
const [evidence, setEvidence] = useState("");
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const record = useMutation({
|
||||
mutationFn: () => issuesApi.resolveRecoveryAction(issueId, {
|
||||
actionId: blocker.recoveryActionId!, outcome: "restored", sourceIssueStatus: issueStatus,
|
||||
resolutionNote: evidence.trim(),
|
||||
executionReconciliation: {
|
||||
runId: blocker.runId!, providerStopped: true, actionOutcome: "mixed",
|
||||
outcomeEvidence: "This request records recovered workspace files only. It does not replay the source run or certify its external action outcomes.",
|
||||
workspaceRepairEvidence: evidence.trim(),
|
||||
},
|
||||
}),
|
||||
onSuccess: onRecorded,
|
||||
});
|
||||
if (!blocker.workspaceRepairRequired || !blocker.canRecordWorkspaceRepair || blocker.cause !== "legacy_execution_requires_reconciliation"
|
||||
|| !blocker.recoveryActionId || !blocker.runId) return null;
|
||||
return <section aria-label="Record workspace file recovery" className="flex w-full flex-col gap-2">
|
||||
{record.isSuccess ? <p role="status">File recovery recorded. The task status is unchanged. Continue the task when it is ready.</p>
|
||||
: canManage ? <>
|
||||
<Label htmlFor={noteId}>Recovered files and verification</Label>
|
||||
<Textarea id={noteId} value={evidence} onChange={event => setEvidence(event.target.value)} maxLength={12_000}
|
||||
placeholder="Describe how you recovered and verified the files from the original workspace. Include the backup or artifact link."
|
||||
disabled={record.isPending} />
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox id={confirmationId} checked={confirmed} onCheckedChange={value => setConfirmed(value === true)} disabled={record.isPending} />
|
||||
<Label htmlFor={confirmationId}>I recovered and verified the original workspace files.</Label>
|
||||
</div>
|
||||
<p className="text-muted-foreground">This records file recovery. It keeps the current task status and does not start a run. Paperclip verifies that the original execution stopped.</p>
|
||||
<div className="flex justify-end">
|
||||
<Button disabled={record.isPending || !confirmed || evidence.trim().length < 20} onClick={() => record.mutate()}>
|
||||
{record.isPending ? "Recording…" : "Record file recovery"}
|
||||
</Button>
|
||||
</div>
|
||||
{record.isError && <p role="alert" className="text-destructive">{record.error.message}</p>}
|
||||
</> : <p className="text-muted-foreground">A board member with runtime access can record verified file recovery here.</p>}
|
||||
</section>;
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { WorkspaceRuntimeService } from "@paperclipai/shared";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
buildWorkspaceRuntimeControlItems,
|
||||
buildWorkspaceRuntimeControlSections,
|
||||
buildWorkspaceServiceControlEntries,
|
||||
resolveWorkspaceServiceControlRequests,
|
||||
@@ -177,108 +176,6 @@ describe("buildWorkspaceRuntimeControlSections", () => {
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("surfaces running stale runtime services separately from updated commands", () => {
|
||||
const sections = buildWorkspaceRuntimeControlSections({
|
||||
runtimeConfig: {
|
||||
commands: [
|
||||
{ id: "web", name: "web", kind: "service", command: "pnpm dev:once --tailscale-auth" },
|
||||
],
|
||||
},
|
||||
runtimeServices: [
|
||||
createRuntimeService({
|
||||
id: "service-web",
|
||||
serviceName: "web",
|
||||
status: "running",
|
||||
command: "pnpm dev",
|
||||
}),
|
||||
],
|
||||
canStartServices: true,
|
||||
canRunJobs: true,
|
||||
});
|
||||
|
||||
expect(sections.services).toEqual([
|
||||
expect.objectContaining({
|
||||
title: "web",
|
||||
statusLabel: "stopped",
|
||||
command: "pnpm dev:once --tailscale-auth",
|
||||
runtimeServiceId: null,
|
||||
}),
|
||||
]);
|
||||
expect(sections.otherServices).toEqual([
|
||||
expect.objectContaining({
|
||||
title: "web",
|
||||
statusLabel: "running",
|
||||
command: "pnpm dev",
|
||||
runtimeServiceId: "service-web",
|
||||
disabledReason: "This runtime service no longer matches a configured workspace command.",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("surfaces running stale runtime services separately from updated commands", () => {
|
||||
const sections = buildWorkspaceRuntimeControlSections({
|
||||
runtimeConfig: {
|
||||
commands: [
|
||||
{ id: "web", name: "web", kind: "service", command: "pnpm dev:once --tailscale-auth" },
|
||||
],
|
||||
},
|
||||
runtimeServices: [
|
||||
createRuntimeService({
|
||||
id: "service-web",
|
||||
serviceName: "web",
|
||||
status: "running",
|
||||
command: "pnpm dev",
|
||||
}),
|
||||
],
|
||||
canStartServices: true,
|
||||
canRunJobs: true,
|
||||
});
|
||||
|
||||
expect(sections.services).toEqual([
|
||||
expect.objectContaining({
|
||||
title: "web",
|
||||
statusLabel: "stopped",
|
||||
command: "pnpm dev:once --tailscale-auth",
|
||||
runtimeServiceId: null,
|
||||
}),
|
||||
]);
|
||||
expect(sections.otherServices).toEqual([
|
||||
expect.objectContaining({
|
||||
title: "web",
|
||||
statusLabel: "running",
|
||||
command: "pnpm dev",
|
||||
runtimeServiceId: "service-web",
|
||||
disabledReason: "This runtime service no longer matches a configured workspace command.",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildWorkspaceRuntimeControlItems", () => {
|
||||
it("keeps the legacy flat export shape for stale importers", () => {
|
||||
const items = buildWorkspaceRuntimeControlItems({
|
||||
runtimeConfig: {
|
||||
commands: [
|
||||
{ id: "web", name: "web", kind: "service", command: "pnpm dev" },
|
||||
{ id: "db-migrate", name: "db:migrate", kind: "job", command: "pnpm db:migrate" },
|
||||
],
|
||||
},
|
||||
runtimeServices: [
|
||||
createRuntimeService({ id: "service-web", serviceName: "web", status: "running" }),
|
||||
],
|
||||
canStartServices: true,
|
||||
canRunJobs: true,
|
||||
});
|
||||
|
||||
expect(items).toHaveLength(1);
|
||||
expect(items[0]).toMatchObject({
|
||||
title: "web",
|
||||
status: "running",
|
||||
statusLabel: "running",
|
||||
runtimeServiceId: "service-web",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("WorkspaceRuntimeControls", () => {
|
||||
@@ -628,36 +525,6 @@ describe("WorkspaceRuntimeControls", () => {
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("accepts the legacy items prop without crashing", () => {
|
||||
const items = buildWorkspaceRuntimeControlItems({
|
||||
runtimeConfig: {
|
||||
commands: [
|
||||
{ id: "web", name: "web", kind: "service", command: "pnpm dev" },
|
||||
],
|
||||
},
|
||||
runtimeServices: [],
|
||||
canStartServices: false,
|
||||
});
|
||||
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(withQueryClient(
|
||||
<WorkspaceRuntimeControls
|
||||
items={items}
|
||||
emptyMessage="No runtime services have been started yet."
|
||||
disabledHint="Add runtime settings first."
|
||||
onAction={vi.fn()}
|
||||
/>,
|
||||
));
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain("Services");
|
||||
expect(container.textContent).toContain("Add runtime settings first.");
|
||||
expect(Array.from(container.querySelectorAll("button")).map((button) => button.textContent?.trim())).toEqual(["Start"]);
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildWorkspaceServiceControlEntries", () => {
|
||||
|
||||
@@ -51,30 +51,12 @@ export type WorkspaceRuntimeControlSections = {
|
||||
otherServices: WorkspaceRuntimeControlItem[];
|
||||
};
|
||||
|
||||
type LegacyWorkspaceRuntimeControlItem = WorkspaceRuntimeControlItem & {
|
||||
status?: string | null;
|
||||
};
|
||||
|
||||
type WorkspaceRuntimeControlsProps = {
|
||||
sections: WorkspaceRuntimeControlSections;
|
||||
items?: never;
|
||||
isPending?: boolean;
|
||||
pendingRequest?: WorkspaceRuntimeControlRequest | null;
|
||||
serviceEmptyMessage?: string;
|
||||
jobEmptyMessage?: string;
|
||||
emptyMessage?: never;
|
||||
disabledHint?: string | null;
|
||||
onAction: (request: WorkspaceRuntimeControlRequest) => void;
|
||||
className?: string;
|
||||
square?: boolean;
|
||||
} | {
|
||||
sections?: never;
|
||||
items: LegacyWorkspaceRuntimeControlItem[];
|
||||
isPending?: boolean;
|
||||
pendingRequest?: WorkspaceRuntimeControlRequest | null;
|
||||
serviceEmptyMessage?: never;
|
||||
jobEmptyMessage?: never;
|
||||
emptyMessage?: string;
|
||||
disabledHint?: string | null;
|
||||
onAction: (request: WorkspaceRuntimeControlRequest) => void;
|
||||
className?: string;
|
||||
@@ -194,18 +176,6 @@ export function buildWorkspaceRuntimeControlSections(input: {
|
||||
};
|
||||
}
|
||||
|
||||
export function buildWorkspaceRuntimeControlItems(input: {
|
||||
runtimeConfig: Record<string, unknown> | null | undefined;
|
||||
runtimeServices: WorkspaceRuntimeService[] | null | undefined;
|
||||
canStartServices: boolean;
|
||||
canRunJobs?: boolean;
|
||||
}): LegacyWorkspaceRuntimeControlItem[] {
|
||||
return buildWorkspaceRuntimeControlSections(input).services.map((item) => ({
|
||||
...item,
|
||||
status: item.statusLabel,
|
||||
}));
|
||||
}
|
||||
|
||||
export function getRunningRuntimeServiceUrl(
|
||||
sections: WorkspaceRuntimeControlSections,
|
||||
) {
|
||||
@@ -537,27 +507,16 @@ function CommandSection({
|
||||
|
||||
export function WorkspaceRuntimeControls({
|
||||
sections,
|
||||
items,
|
||||
isPending = false,
|
||||
pendingRequest = null,
|
||||
serviceEmptyMessage = "No services are configured for this workspace.",
|
||||
jobEmptyMessage = "No one-shot jobs are configured for this workspace.",
|
||||
emptyMessage,
|
||||
disabledHint = null,
|
||||
onAction,
|
||||
className,
|
||||
square,
|
||||
}: WorkspaceRuntimeControlsProps) {
|
||||
const resolvedSections = sections ?? {
|
||||
services: (items ?? []).map((item) => ({
|
||||
...item,
|
||||
statusLabel: item.statusLabel ?? item.status ?? "stopped",
|
||||
})),
|
||||
jobs: [],
|
||||
otherServices: [],
|
||||
};
|
||||
const resolvedServiceEmptyMessage = emptyMessage ?? serviceEmptyMessage;
|
||||
const runningCount = [...resolvedSections.services, ...resolvedSections.otherServices].filter(
|
||||
const runningCount = [...sections.services, ...sections.otherServices].filter(
|
||||
(item) => item.statusLabel === "running" || item.statusLabel === "starting",
|
||||
).length;
|
||||
const visibleDisabledHint = runningCount > 0 || disabledHint === null ? null : disabledHint;
|
||||
@@ -580,8 +539,8 @@ export function WorkspaceRuntimeControls({
|
||||
{runningCount > 0 ? `${runningCount} services running` : "No services running"}
|
||||
</Badge>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{resolvedSections.jobs.length > 0
|
||||
? `${resolvedSections.jobs.length} job${resolvedSections.jobs.length === 1 ? "" : "s"} available to run on demand.`
|
||||
{sections.jobs.length > 0
|
||||
? `${sections.jobs.length} job${sections.jobs.length === 1 ? "" : "s"} available to run on demand.`
|
||||
: "Each command can be controlled independently."}
|
||||
</span>
|
||||
</div>
|
||||
@@ -592,8 +551,8 @@ export function WorkspaceRuntimeControls({
|
||||
<CommandSection
|
||||
title="Services"
|
||||
description="Long-running commands that Paperclip can supervise for this workspace."
|
||||
items={resolvedSections.services}
|
||||
emptyMessage={resolvedServiceEmptyMessage}
|
||||
items={sections.services}
|
||||
emptyMessage={serviceEmptyMessage}
|
||||
disabledHint={visibleDisabledHint}
|
||||
isPending={isPending}
|
||||
pendingRequest={pendingRequest}
|
||||
@@ -604,7 +563,7 @@ export function WorkspaceRuntimeControls({
|
||||
<CommandSection
|
||||
title="Jobs"
|
||||
description="One-shot commands that run now and exit when they finish."
|
||||
items={resolvedSections.jobs}
|
||||
items={sections.jobs}
|
||||
emptyMessage={jobEmptyMessage}
|
||||
isPending={isPending}
|
||||
pendingRequest={pendingRequest}
|
||||
@@ -612,11 +571,11 @@ export function WorkspaceRuntimeControls({
|
||||
square={square}
|
||||
/>
|
||||
|
||||
{resolvedSections.otherServices.length > 0 ? (
|
||||
{sections.otherServices.length > 0 ? (
|
||||
<CommandSection
|
||||
title="Untracked services"
|
||||
description="Running services that no longer match the current workspace command config."
|
||||
items={resolvedSections.otherServices}
|
||||
items={sections.otherServices}
|
||||
emptyMessage=""
|
||||
isPending={isPending}
|
||||
pendingRequest={pendingRequest}
|
||||
|
||||
@@ -68,6 +68,7 @@ describe("CompanySettingsNav", () => {
|
||||
it("maps company settings routes to the expected shared tab value", () => {
|
||||
expect(getCompanySettingsTab("/company/settings")).toBe("general");
|
||||
expect(getCompanySettingsTab("/PAP/company/settings")).toBe("general");
|
||||
expect(getCompanySettingsTab("/PAP/company/settings/connections")).toBe("connections");
|
||||
expect(getCompanySettingsTab("/company/settings/environments")).toBe("instance-environments");
|
||||
expect(getCompanySettingsTab("/company/export")).toBe("export");
|
||||
expect(getCompanySettingsTab("/PAP/company/export")).toBe("export");
|
||||
@@ -93,8 +94,10 @@ describe("CompanySettingsNav", () => {
|
||||
root: ReturnType<typeof createRoot>,
|
||||
hiddenSettings?: string[],
|
||||
cloud?: { managed: boolean },
|
||||
fastResponsesEnabled = true,
|
||||
) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
queryClient.setQueryData(queryKeys.instance.experimentalSettings, { enableFastResponses: fastResponsesEnabled });
|
||||
queryClient.setQueryData(queryKeys.health, {
|
||||
status: "ok",
|
||||
...(hiddenSettings ? { hiddenSettings } : {}),
|
||||
@@ -107,6 +110,13 @@ describe("CompanySettingsNav", () => {
|
||||
);
|
||||
}
|
||||
|
||||
it("hides Connections while fast responses are disabled", async () => {
|
||||
const root = createRoot(container);
|
||||
await act(async () => { renderNav(root, undefined, undefined, false); });
|
||||
expect(pageTabBarMock.mock.calls.at(-1)?.[0]?.items).not.toContainEqual({ value: "connections", label: "Connections" });
|
||||
await act(async () => { root.unmount(); });
|
||||
});
|
||||
|
||||
it("renders the active tab and navigates when a different tab is selected", async () => {
|
||||
currentPathname = "/PAP/company/settings/members";
|
||||
const root = createRoot(container);
|
||||
@@ -127,6 +137,7 @@ describe("CompanySettingsNav", () => {
|
||||
{ value: "secrets", label: "Secrets" },
|
||||
{ value: "instance-profile", label: "Profile" },
|
||||
{ value: "instance-environments", label: "Environments" },
|
||||
{ value: "connections", label: "Connections" },
|
||||
{ value: "instance-access", label: "Access" },
|
||||
{ value: "instance-experimental", label: "Experimental" },
|
||||
{ value: "instance-plugins", label: "Plugins" },
|
||||
@@ -168,6 +179,7 @@ describe("CompanySettingsNav", () => {
|
||||
"secrets",
|
||||
"instance-profile",
|
||||
"instance-environments",
|
||||
"connections",
|
||||
"instance-access",
|
||||
"instance-experimental",
|
||||
"instance-adapters",
|
||||
|
||||
@@ -2,6 +2,7 @@ import { PageTabBar } from "@/components/PageTabBar";
|
||||
import { Tabs } from "@/components/ui/tabs";
|
||||
import { useCloudInstance } from "@/hooks/useCloudInstance";
|
||||
import { useHiddenSettings } from "@/hooks/useHiddenSettings";
|
||||
import { useFastResponsesEnabled } from "@/hooks/useFastResponsesEnabled";
|
||||
import { INSTANCE_SETTINGS_PATH_PREFIX } from "@/lib/instance-settings";
|
||||
import { useLocation, useNavigate } from "@/lib/router";
|
||||
|
||||
@@ -13,6 +14,7 @@ const items = [
|
||||
{ value: "secrets", label: "Secrets", href: "/company/settings/secrets" },
|
||||
{ value: "instance-profile", label: "Profile", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/profile` },
|
||||
{ value: "instance-environments", label: "Environments", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/environments` },
|
||||
{ value: "connections", label: "Connections", href: "/company/settings/connections" },
|
||||
{ value: "instance-access", label: "Access", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/access` },
|
||||
{ value: "instance-experimental", label: "Experimental", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/experimental` },
|
||||
{ value: "instance-plugins", label: "Plugins", href: `${INSTANCE_SETTINGS_PATH_PREFIX}/plugins` },
|
||||
@@ -36,6 +38,10 @@ const hiddenSettingKeyByTab: Partial<Record<CompanySettingsTab, string>> = {
|
||||
};
|
||||
|
||||
export function getCompanySettingsTab(pathname: string): CompanySettingsTab {
|
||||
if (pathname.includes("/company/settings/connections")) {
|
||||
return "connections";
|
||||
}
|
||||
|
||||
if (pathname.includes(`${INSTANCE_SETTINGS_PATH_PREFIX}/profile`)) {
|
||||
return "instance-profile";
|
||||
}
|
||||
@@ -96,11 +102,13 @@ export function CompanySettingsNav() {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const { hidden: hiddenSettings } = useHiddenSettings();
|
||||
const { enabled: fastResponsesEnabled } = useFastResponsesEnabled();
|
||||
// Import is floored server-side on cloud-managed instances (403 cloud_managed), so the
|
||||
// tab is suppressed there rather than dead-ending.
|
||||
const isCloud = Boolean(useCloudInstance());
|
||||
const activeTab = getCompanySettingsTab(location.pathname);
|
||||
const visibleItems = items.filter((item) => {
|
||||
if (item.value === "connections" && !fastResponsesEnabled) return false;
|
||||
if (item.value === "import" && isCloud) return false;
|
||||
const hiddenKey = hiddenSettingKeyByTab[item.value];
|
||||
return !hiddenKey || !hiddenSettings.has(hiddenKey);
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Upload } from "lucide-react";
|
||||
|
||||
/** The target can be the host frame when its tab header is rendered by a portal. */
|
||||
export function ArtifactDropzone({ children, onUpload, enabled = true, target }: {
|
||||
children: ReactNode;
|
||||
onUpload: (files: File[]) => void;
|
||||
enabled?: boolean;
|
||||
target?: HTMLElement | null;
|
||||
}) {
|
||||
const rootRef = useRef<HTMLElement>(null);
|
||||
const uploadRef = useRef(onUpload);
|
||||
uploadRef.current = onUpload;
|
||||
const [dragging, setDragging] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const element = target ?? rootRef.current;
|
||||
setDragging(false);
|
||||
if (!enabled || !element) return;
|
||||
let depth = 0;
|
||||
const hasFiles = (event: DragEvent) => Array.from(event.dataTransfer?.types ?? []).includes("Files");
|
||||
const enter = (event: DragEvent) => {
|
||||
if (!hasFiles(event)) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
depth += 1;
|
||||
setDragging(true);
|
||||
};
|
||||
const over = (event: DragEvent) => {
|
||||
if (!hasFiles(event)) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
|
||||
};
|
||||
const leave = (event: DragEvent) => {
|
||||
if (!hasFiles(event)) return;
|
||||
event.stopPropagation();
|
||||
depth = Math.max(0, depth - 1);
|
||||
if (depth === 0) setDragging(false);
|
||||
};
|
||||
const drop = (event: DragEvent) => {
|
||||
if (!hasFiles(event)) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
depth = 0;
|
||||
setDragging(false);
|
||||
const files = Array.from(event.dataTransfer?.files ?? []);
|
||||
if (files.length) uploadRef.current(files);
|
||||
};
|
||||
element.addEventListener("dragenter", enter);
|
||||
element.addEventListener("dragover", over);
|
||||
element.addEventListener("dragleave", leave);
|
||||
element.addEventListener("drop", drop);
|
||||
return () => {
|
||||
element.removeEventListener("dragenter", enter);
|
||||
element.removeEventListener("dragover", over);
|
||||
element.removeEventListener("dragleave", leave);
|
||||
element.removeEventListener("drop", drop);
|
||||
};
|
||||
}, [enabled, target]);
|
||||
|
||||
const overlay = dragging ? (
|
||||
<div data-artifact-drop-overlay role="status" className="pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 border-2 border-dashed border-primary bg-background/95 px-6 text-center">
|
||||
<Upload aria-hidden="true" className="size-6 text-primary" />
|
||||
<p className="text-sm font-medium">Drop files to add them to this task</p>
|
||||
</div>
|
||||
) : null;
|
||||
return (
|
||||
<section ref={rootRef} aria-label={enabled ? "Artifact uploads" : undefined} className="relative h-full min-h-0">
|
||||
{children}
|
||||
{target && overlay ? createPortal(overlay, target) : overlay}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { SidePanelFrame } from "@/components/side-panel/SidePanelFrame";
|
||||
import { ArtifactDropzone } from "./ArtifactDropzone";
|
||||
import { ArtifactUploadButton, ArtifactUploadContent, type ArtifactUploadEntry } from "./ArtifactUploadControls";
|
||||
export type { ArtifactUploadEntry } from "./ArtifactUploadControls";
|
||||
|
||||
/** Standalone composition of the same controls used by task panel hosts. */
|
||||
export function ArtifactUploadArea({ children, header, empty = false, entries = [], onUpload, onRetry, onDismiss }: {
|
||||
children?: ReactNode;
|
||||
header?: ReactNode;
|
||||
empty?: boolean;
|
||||
entries?: ArtifactUploadEntry[];
|
||||
onUpload: (files: File[]) => void;
|
||||
onRetry?: (id: string) => void;
|
||||
onDismiss?: (id: string) => void;
|
||||
}) {
|
||||
return <ArtifactDropzone onUpload={onUpload}>
|
||||
<SidePanelFrame presentation="sheet" label="Task artifacts" header={header} trailingControls={<ArtifactUploadButton onUpload={onUpload} />}>
|
||||
<ArtifactUploadContent empty={empty} entries={entries} onRetry={onRetry} onDismiss={onDismiss}>{children}</ArtifactUploadContent>
|
||||
</SidePanelFrame>
|
||||
</ArtifactDropzone>;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { useRef, type ReactNode } from "react";
|
||||
import { FileUp, Loader2, Upload, X } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface ArtifactUploadEntry {
|
||||
id: string;
|
||||
filename: string;
|
||||
status: "uploading" | "error";
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export function ArtifactUploadButton({ onUpload }: { onUpload: (files: File[]) => void }) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
return <>
|
||||
<input ref={inputRef} type="file" multiple aria-label="Choose artifact files" className="hidden" onChange={(event) => {
|
||||
const files = Array.from(event.target.files ?? []);
|
||||
event.target.value = "";
|
||||
if (files.length) onUpload(files);
|
||||
}} />
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button variant="ghost" size="icon-sm" aria-label="Upload files" className="size-(--sz-44px) bg-transparent text-muted-foreground hover:bg-transparent hover:text-foreground dark:hover:bg-transparent sm:size-9" onClick={() => inputRef.current?.click()}>
|
||||
<Upload aria-hidden="true" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Upload files</TooltipContent>
|
||||
</Tooltip>
|
||||
</>;
|
||||
}
|
||||
|
||||
export function ArtifactUploadContent({ children, empty = false, entries = [], onRetry, onDismiss }: {
|
||||
children?: ReactNode;
|
||||
empty?: boolean;
|
||||
entries?: ArtifactUploadEntry[];
|
||||
onRetry?: (id: string) => void;
|
||||
onDismiss?: (id: string) => void;
|
||||
}) {
|
||||
return <div className="flex min-h-full flex-col gap-3">
|
||||
{entries.length > 0 ? <ul className="flex flex-col gap-2" aria-label="Uploads">
|
||||
{entries.map((entry) => <li key={entry.id} className="flex items-start gap-2 rounded-lg border border-border p-3">
|
||||
{entry.status === "uploading"
|
||||
? <Loader2 aria-hidden="true" className="mt-0.5 size-4 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none" />
|
||||
: <FileUp aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-muted-foreground" />}
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
<span className="break-words text-sm font-medium">{entry.filename}</span>
|
||||
<span role={entry.status === "error" ? "alert" : "status"} className={cn("text-xs", entry.status === "error" ? "text-destructive" : "text-muted-foreground")}>
|
||||
{entry.status === "uploading" ? "Uploading…" : entry.error ?? "Upload failed. Try again."}
|
||||
</span>
|
||||
</div>
|
||||
{entry.status === "error" ? <div className="flex shrink-0 items-center gap-1">
|
||||
{onRetry ? <Button variant="ghost" size="sm" onClick={() => onRetry(entry.id)}>Retry</Button> : null}
|
||||
{onDismiss ? <Button variant="ghost" size="icon-sm" aria-label={`Dismiss upload: ${entry.filename}`} onClick={() => onDismiss(entry.id)}><X aria-hidden="true" /></Button> : null}
|
||||
</div> : null}
|
||||
</li>)}
|
||||
</ul> : null}
|
||||
{empty ? <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 py-12 text-center">
|
||||
<FileUp aria-hidden="true" className="size-6 text-muted-foreground" />
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="text-sm font-medium">Add files to this task</p>
|
||||
<p className="text-sm text-muted-foreground">Drop files anywhere in this panel or use the upload icon.</p>
|
||||
</div>
|
||||
</div> : children}
|
||||
</div>;
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useToast } from "@/context/ToastContext";
|
||||
import { Link } from "@/lib/router";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { useChatConnectorsEnabled, chatProviderVisible } from "@/hooks/useChatConnectorsEnabled";
|
||||
import { issuesApi } from "@/api/issues";
|
||||
@@ -125,6 +126,7 @@ export function useIssueChatBinding(companyId: string, issueId: string) {
|
||||
}
|
||||
|
||||
type ConnectedTaskProps = {
|
||||
className?: string;
|
||||
attachments?: IssueAttachment[];
|
||||
companyId: string;
|
||||
issueId: string;
|
||||
@@ -145,6 +147,7 @@ export function ExternallyConnectedTaskBanner(props: ConnectedTaskProps) {
|
||||
}
|
||||
|
||||
function ConnectedTaskComposer({
|
||||
className,
|
||||
attachments = [],
|
||||
companyId,
|
||||
issueId,
|
||||
@@ -483,7 +486,7 @@ function ConnectedTaskComposer({
|
||||
return (
|
||||
<section
|
||||
aria-label="External conversation"
|
||||
className="space-y-3 rounded-lg border border-border bg-muted/40 p-3 text-sm"
|
||||
className={cn("task-context-notice space-y-3", className)}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="flex min-w-0 flex-1 basis-64 items-center gap-3">
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { DecisionHistoryTable } from "./DecisionHistory";
|
||||
|
||||
vi.mock("@/context/CompanyContext", () => ({
|
||||
useCompany: () => ({ selectedCompany: { issuePrefix: "ACM" } }),
|
||||
}));
|
||||
|
||||
describe("model history setup links", () => {
|
||||
it.each([
|
||||
[false, true, "/ACM/company/settings/connections", "Configure a decision model"],
|
||||
[false, false, "/ACM/company/settings", "Configure a decision model"],
|
||||
[true, true, "/ACM/company/settings/connections", "Configure fast response"],
|
||||
[true, false, "/ACM/company/settings/instance/experimental", "Enable experimental fast responses"],
|
||||
] as const)("routes setup with fast response %s and experiment %s", (fastResponse, connectionsEnabled, href, label) => {
|
||||
const container = document.createElement("div");
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
flushSync(() => root.render(
|
||||
<MemoryRouter>
|
||||
<DecisionHistoryTable entries={[]} fastResponse={fastResponse} connectionsEnabled={connectionsEnabled} />
|
||||
</MemoryRouter>,
|
||||
));
|
||||
expect(container.querySelector("a")?.getAttribute("href")).toBe(href);
|
||||
expect(container.querySelector("a")?.textContent).toBe(label);
|
||||
} finally {
|
||||
flushSync(() => root.unmount());
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -4,19 +4,21 @@ import { decisionModelsApi } from "@/api/decision-models";
|
||||
import { Link } from "@/lib/router";
|
||||
import { formatDateTime, formatTokens, formatDetailedCents } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useFastResponsesEnabled } from "@/hooks/useFastResponsesEnabled";
|
||||
|
||||
export function DecisionHistoryTable({ entries }: { entries: DecisionHistoryEntry[] }) {
|
||||
if (!entries.length) return <p className="text-sm text-muted-foreground">No decision requests in this period. <Link to="/company/settings" className="underline underline-offset-4">Configure a decision model</Link> to run a test.</p>;
|
||||
export function DecisionHistoryTable({ entries, fastResponse = false, connectionsEnabled = true }: { entries: (DecisionHistoryEntry & { publicationStatus?: string; connectionName?: string | null })[]; fastResponse?: boolean; connectionsEnabled?: boolean }) {
|
||||
if (!entries.length) return <p className="text-sm text-muted-foreground">{fastResponse ? "No fast responses in this period." : "No decision requests in this period."} <Link to={connectionsEnabled ? "/company/settings/connections" : fastResponse ? "/company/settings/instance/experimental" : "/company/settings"} className="underline underline-offset-4">{fastResponse ? connectionsEnabled ? "Configure fast response" : "Enable experimental fast responses" : "Configure a decision model"}</Link> to run a test.</p>;
|
||||
return <div className="space-y-3">
|
||||
<p className="text-xs text-muted-foreground">Recent requests. Inputs and answers are not retained.</p>
|
||||
<div className="overflow-x-auto"><table className="w-full text-sm" aria-label="Decision requests">
|
||||
<thead><tr className="border-b border-border text-muted-foreground">{["When / feature", "Responsible", "Task", "Model", "Status", "Duration", "Tokens in / out", "Cost"].map(label => <th key={label} className="px-3 py-2 text-left font-medium">{label}</th>)}</tr></thead>
|
||||
<p className="text-xs text-muted-foreground">Recent requests. Inputs are not retained.</p>
|
||||
<div className="overflow-x-auto"><table className="w-full text-sm" aria-label={fastResponse ? "Fast responses" : "Decision requests"}>
|
||||
<thead><tr className="border-b border-border text-muted-foreground">{["When / feature", "Responsible", "Task", ...(fastResponse ? ["Connection"] : []), "Model", "Status", "Duration", "Tokens in / out", "Cost"].map(label => <th key={label} className="px-3 py-2 text-left font-medium">{label}</th>)}</tr></thead>
|
||||
<tbody>{entries.map(row => <tr key={row.id} className="border-b border-border last:border-0">
|
||||
<td className="px-3 py-3"><div className="whitespace-nowrap">{formatDateTime(row.startedAt)}</div><div className="text-xs text-muted-foreground">{row.feature === "settings.test" ? "Setup test" : row.feature}</div></td>
|
||||
<td className="px-3 py-3">{row.actorType === "system" ? "Paperclip services" : row.userName ?? (row.responsibleUserId === "local-board" ? "Board" : "Former user")}</td>
|
||||
<td className="px-3 py-3">{row.issueId ? <Link className="underline underline-offset-4" to={`/issues/${row.issueIdentifier ?? row.issueId}`}>{row.issueIdentifier ?? "View task"}</Link> : "—"}</td>
|
||||
{fastResponse && <td className="px-3 py-3">{row.connectionName ?? (row.connectionId ? "Removed connection" : "—")}</td>}
|
||||
<td className="px-3 py-3 font-mono text-xs">{row.model}</td>
|
||||
<td className="px-3 py-3"><div>{row.status === "succeeded" ? "Succeeded" : row.status === "running" ? "Running" : row.status === "unknown" ? "Unresolved" : "Failed"}</div>{row.errorCode && <div className="text-xs text-muted-foreground">{row.errorCode.replaceAll("_", " ")}</div>}</td>
|
||||
<td className="px-3 py-3"><div>{row.status === "succeeded" ? "Succeeded" : row.status === "running" ? "Running" : row.status === "unknown" ? "Unresolved" : row.status === "skipped" ? "Skipped" : row.status === "pending" ? "Pending" : "Failed"}</div>{row.publicationStatus && <div className="text-xs text-muted-foreground">{row.publicationStatus}</div>}{row.errorCode && <div className="text-xs text-muted-foreground">{row.errorCode.replaceAll("_", " ")}</div>}</td>
|
||||
<td className="px-3 py-3 font-mono">{row.durationMs === null ? "—" : `${(row.durationMs / 1000).toFixed(1)}s`}</td>
|
||||
<td className="whitespace-nowrap px-3 py-3 font-mono">{row.inputTokens === null ? "—" : formatTokens(row.inputTokens)} / {row.outputTokens === null ? "—" : formatTokens(row.outputTokens)}</td>
|
||||
<td className="px-3 py-3 font-mono"><div>{row.costCents === null ? "Unknown" : formatDetailedCents(row.costCents)}</div>{row.costStatus !== "unpriced" && row.costStatus && <span className="text-xs text-muted-foreground">{row.costStatus === "estimated" ? "Estimated" : "Reported"}</span>}</td>
|
||||
@@ -25,8 +27,9 @@ export function DecisionHistoryTable({ entries }: { entries: DecisionHistoryEntr
|
||||
</div>;
|
||||
}
|
||||
export function DecisionHistory({ companyId, from, to }: { companyId: string; from?: string | null; to?: string | null }) {
|
||||
const { enabled } = useFastResponsesEnabled();
|
||||
const query = useQuery({ queryKey: ["decision-history", companyId, from, to], queryFn: () => decisionModelsApi.history(companyId, from, to), refetchInterval: q => q.state.data?.some(row => row.status === "running") ? 5000 : false });
|
||||
if (query.isPending) return <p className="text-sm text-muted-foreground">Loading decision requests…</p>;
|
||||
if (query.error) return <div role="alert" className="space-y-2"><p className="text-sm text-destructive">Could not load decision requests.</p><Button variant="outline" onClick={() => void query.refetch()}>Try again</Button></div>;
|
||||
return <DecisionHistoryTable entries={query.data ?? []} />;
|
||||
return <DecisionHistoryTable entries={query.data ?? []} connectionsEnabled={enabled} />;
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { expect, it, vi } from "vitest";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { decisionModelsApi } from "@/api/decision-models";
|
||||
import { DecisionModelSettingsSection, DecisionModelSettingsView } from "./DecisionModelSettings";
|
||||
import { choices, configured, result } from "../../../storybook/stories/decision-models/fixtures";
|
||||
import { choices, configured, result } from "../../../storybook/support/decision-models/fixtures";
|
||||
|
||||
vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: "company-storybook" }) }));
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
@@ -43,7 +43,7 @@ export function DecisionModelSettingsView({ settings, choices, saving, testing,
|
||||
const unavailable = result && result.status !== "succeeded" ? failureMessages[result.status === "unavailable" ? result.reason : result.errorCode] ?? "The decision could not be completed. Review its entry in Costs." : null;
|
||||
return <section aria-labelledby="decision-model-heading" className="max-w-2xl space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h2 id="decision-model-heading" className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Decision model</h2>
|
||||
<h2 id="decision-model-heading" className="text-lg font-semibold">Decision model</h2>
|
||||
<Link to="/activity/costs?tab=decisions" className="text-sm underline underline-offset-4">View usage</Link>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">Choose the shared connection Paperclip uses for optional decision features. API usage is charged to this connection.</p>
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { fastResponsesApi } from "@/api/fast-responses";
|
||||
import { DecisionHistoryTable } from "@/components/decision-models/DecisionHistory";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useFastResponsesEnabled } from "@/hooks/useFastResponsesEnabled";
|
||||
export function FastResponseHistory({
|
||||
companyId,
|
||||
from,
|
||||
to,
|
||||
}: {
|
||||
companyId: string;
|
||||
from?: string | null;
|
||||
to?: string | null;
|
||||
}) {
|
||||
const { enabled } = useFastResponsesEnabled();
|
||||
const query = useQuery({
|
||||
queryKey: ["fast-response-history", companyId, from, to],
|
||||
queryFn: () =>
|
||||
fastResponsesApi.history(companyId, from ?? undefined, to ?? undefined),
|
||||
refetchInterval: (q) =>
|
||||
q.state.data?.some(
|
||||
(r) =>
|
||||
["pending", "running"].includes(r.status) ||
|
||||
["pending", "streaming", "retry"].includes(r.publicationStatus),
|
||||
)
|
||||
? 3000
|
||||
: false,
|
||||
});
|
||||
if (query.isPending)
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">Loading fast responses…</p>
|
||||
);
|
||||
if (query.error)
|
||||
return (
|
||||
<div role="alert">
|
||||
<p className="text-sm text-destructive">
|
||||
Could not load fast responses.
|
||||
</p>
|
||||
<Button variant="outline" onClick={() => void query.refetch()}>
|
||||
Try again
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
return <DecisionHistoryTable entries={query.data ?? []} fastResponse connectionsEnabled={enabled} />;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { updateFastResponseSchema } from "@paperclipai/shared";
|
||||
import { FastResponseSettingsView } from "./FastResponseSettings";
|
||||
import { choices } from "../../../storybook/support/decision-models/fixtures";
|
||||
vi.mock("@/context/CompanyContext", () => ({
|
||||
useCompany: () => ({ selectedCompanyId: "company-storybook" }),
|
||||
}));
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
it("saves only API settings and keeps the draft across unchanged query refetches", async () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container),
|
||||
onSave = vi.fn();
|
||||
const settings = {
|
||||
companyId: "company-storybook",
|
||||
enabled: false,
|
||||
connectionId: null,
|
||||
grantId: null,
|
||||
provider: null,
|
||||
model: null,
|
||||
allowSponsored: false,
|
||||
};
|
||||
const render = () => (
|
||||
<MemoryRouter>
|
||||
<FastResponseSettingsView
|
||||
settings={{ ...settings }}
|
||||
choices={choices}
|
||||
onSave={onSave}
|
||||
onTest={vi.fn()}
|
||||
/>
|
||||
</MemoryRouter>
|
||||
);
|
||||
try {
|
||||
await act(async () => root.render(render()));
|
||||
await act(async () =>
|
||||
[...container.querySelectorAll("button")]
|
||||
.find((b) => b.textContent?.includes("Company OpenRouter"))!
|
||||
.click(),
|
||||
);
|
||||
await act(async () => root.render(render()));
|
||||
expect(
|
||||
container.querySelector<HTMLInputElement>("input[list]")?.value,
|
||||
).toBe("openai/gpt-oss-120b");
|
||||
await act(async () =>
|
||||
[...container.querySelectorAll("button")]
|
||||
.find((b) => b.textContent === "Save fast response")!
|
||||
.click(),
|
||||
);
|
||||
const saved = onSave.mock.calls[0][0];
|
||||
expect(updateFastResponseSchema.safeParse(saved).success).toBe(true);
|
||||
expect(saved).toMatchObject({
|
||||
enabled: true,
|
||||
allowSponsored: false,
|
||||
connectionId: choices[1]!.id,
|
||||
});
|
||||
expect(saved).not.toHaveProperty("companyId");
|
||||
expect(saved).not.toHaveProperty("provider");
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
it("selects a newly created connection and recommends its default model", async () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container),
|
||||
onSave = vi.fn(),
|
||||
onConnectionChange = vi.fn();
|
||||
const settings = {
|
||||
companyId: "company-storybook",
|
||||
enabled: false,
|
||||
connectionId: null,
|
||||
grantId: null,
|
||||
provider: null,
|
||||
model: null,
|
||||
allowSponsored: true,
|
||||
};
|
||||
try {
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<MemoryRouter>
|
||||
<FastResponseSettingsView
|
||||
settings={settings}
|
||||
choices={choices}
|
||||
newlyConnectedId={choices[1]!.id}
|
||||
onConnectionChange={onConnectionChange}
|
||||
onSave={onSave}
|
||||
onTest={vi.fn()}
|
||||
/>
|
||||
</MemoryRouter>,
|
||||
),
|
||||
);
|
||||
expect(
|
||||
container.querySelector<HTMLInputElement>("input[list]")?.value,
|
||||
).toBe("openai/gpt-oss-120b");
|
||||
await act(async () =>
|
||||
[...container.querySelectorAll("button")]
|
||||
.find((b) => b.textContent === "Save fast response")!
|
||||
.click(),
|
||||
);
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
connectionId: choices[1]!.id,
|
||||
enabled: true,
|
||||
allowSponsored: true,
|
||||
}),
|
||||
);
|
||||
expect(onConnectionChange).toHaveBeenCalledWith(choices[1]!.id);
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,413 @@
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
FAST_RESPONSE_DEFAULT_MODEL,
|
||||
type FastResponseSettings,
|
||||
type AiManagedConnectionSummary,
|
||||
type FastResponseTestResult,
|
||||
type UpdateFastResponse,
|
||||
type AiProvider,
|
||||
} from "@paperclipai/shared";
|
||||
import { fastResponsesApi } from "@/api/fast-responses";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ToggleField } from "@/components/agent-config-primitives";
|
||||
import { ConnectionChoiceList } from "@/features/connections/ConnectionChoiceList";
|
||||
import { AppLogo } from "@/pages/apps/AppLogo";
|
||||
import { ConnectionSetupFlow } from "@/features/connections/ConnectionSetupFlow";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Link } from "@/lib/router";
|
||||
|
||||
const editable = (s: FastResponseSettings): UpdateFastResponse => ({
|
||||
enabled: s.enabled,
|
||||
connectionId: s.connectionId,
|
||||
grantId: s.grantId,
|
||||
model: s.model,
|
||||
allowSponsored: s.allowSponsored,
|
||||
});
|
||||
|
||||
export function FastResponseSettingsView({
|
||||
settings,
|
||||
choices,
|
||||
models = [],
|
||||
saving,
|
||||
testing,
|
||||
error,
|
||||
result,
|
||||
newlyConnectedId,
|
||||
onSave,
|
||||
onTest,
|
||||
onConnectionChange,
|
||||
onAdd,
|
||||
}: {
|
||||
settings: FastResponseSettings;
|
||||
choices: AiManagedConnectionSummary[];
|
||||
models?: Array<{ id: string; label?: string }>;
|
||||
newlyConnectedId?: string | null;
|
||||
saving?: boolean;
|
||||
testing?: boolean;
|
||||
error?: string | null;
|
||||
result?: FastResponseTestResult | null;
|
||||
onAdd?: () => void;
|
||||
onSave: (value: UpdateFastResponse) => void;
|
||||
onTest: () => void;
|
||||
onConnectionChange?: (id: string | null) => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<UpdateFastResponse>(() =>
|
||||
editable(settings),
|
||||
);
|
||||
const modelListId = useId();
|
||||
const revision = JSON.stringify(editable(settings));
|
||||
useEffect(() => {
|
||||
setDraft(editable(settings));
|
||||
onConnectionChange?.(settings.connectionId);
|
||||
}, [revision]);
|
||||
const appliedConnection = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!newlyConnectedId) {
|
||||
appliedConnection.current = null;
|
||||
return;
|
||||
}
|
||||
if (appliedConnection.current === newlyConnectedId) return;
|
||||
const connection = choices.find((row) => row.id === newlyConnectedId);
|
||||
if (!connection) return;
|
||||
appliedConnection.current = newlyConnectedId;
|
||||
setDraft((value) => ({
|
||||
...value,
|
||||
connectionId: connection.id,
|
||||
grantId: connection.grantId,
|
||||
model:
|
||||
connection.provider === "openrouter" ||
|
||||
connection.routing?.kind === "openrouter"
|
||||
? FAST_RESPONSE_DEFAULT_MODEL
|
||||
: (connection.routing?.models[0]?.id ?? null),
|
||||
enabled: value.connectionId ? value.enabled : true,
|
||||
}));
|
||||
onConnectionChange?.(connection.id);
|
||||
}, [newlyConnectedId, choices, onConnectionChange]);
|
||||
const selected = choices.find((c) => c.grantId === draft.grantId);
|
||||
const dirty =
|
||||
draft.enabled !== settings.enabled ||
|
||||
draft.grantId !== settings.grantId ||
|
||||
draft.model !== settings.model ||
|
||||
draft.allowSponsored !== settings.allowSponsored;
|
||||
return (
|
||||
<section className="max-w-2xl space-y-4" aria-label="Fast response">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h2 className="text-lg font-semibold">
|
||||
Fast response
|
||||
</h2>
|
||||
<Link
|
||||
to="/activity/costs?tab=fast-responses"
|
||||
className="text-sm underline underline-offset-4"
|
||||
>
|
||||
View usage
|
||||
</Link>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Send a short acknowledgement while your agent starts work. Usage is
|
||||
charged to the selected shared API connection.
|
||||
</p>
|
||||
<ConnectionChoiceList
|
||||
selectedId={draft.grantId ?? undefined}
|
||||
disabled={saving || testing}
|
||||
choices={choices.map((c) => ({
|
||||
id: c.grantId,
|
||||
name: c.name,
|
||||
description:
|
||||
c.status === "connected" ? "Connected" : "Needs attention",
|
||||
icon: <AppLogo name={c.provider} brandKey={c.provider} size={24} />,
|
||||
}))}
|
||||
onSelect={(grantId) => {
|
||||
const c = choices.find((c) => c.grantId === grantId)!;
|
||||
setDraft((d) => ({
|
||||
...d,
|
||||
connectionId: c.id,
|
||||
grantId,
|
||||
model:
|
||||
c.provider === "openrouter" || c.routing?.kind === "openrouter"
|
||||
? FAST_RESPONSE_DEFAULT_MODEL
|
||||
: (c.routing?.models[0]?.id ?? null),
|
||||
enabled: d.connectionId ? d.enabled : true,
|
||||
}));
|
||||
onConnectionChange?.(c.id);
|
||||
}}
|
||||
/>
|
||||
{!choices.length && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Add a shared API connection in Apps to get started.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center gap-3">
|
||||
{onAdd && (
|
||||
<Button variant="outline" size="sm" onClick={onAdd}>
|
||||
Add connection
|
||||
</Button>
|
||||
)}
|
||||
<Link to="/apps" className="text-sm underline underline-offset-4">
|
||||
Manage connections
|
||||
</Link>
|
||||
</div>
|
||||
{draft.connectionId && (
|
||||
<fieldset disabled={saving || testing} className="space-y-4">
|
||||
{!selected && (
|
||||
<p role="status" className="text-sm text-muted-foreground">
|
||||
The saved connection is unavailable. Disable fast responses or
|
||||
choose another connection.
|
||||
</p>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor={`${modelListId}-input`}
|
||||
className="text-sm font-medium"
|
||||
>
|
||||
Model
|
||||
</label>
|
||||
<Input
|
||||
id={`${modelListId}-input`}
|
||||
list={modelListId}
|
||||
value={draft.model ?? ""}
|
||||
placeholder="Choose or enter a model ID"
|
||||
onChange={(e) =>
|
||||
setDraft((d) => ({ ...d, model: e.target.value || null }))
|
||||
}
|
||||
/>
|
||||
<datalist id={modelListId}>
|
||||
{models.map((m) => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{m.label ?? m.id}
|
||||
</option>
|
||||
))}
|
||||
</datalist>
|
||||
</div>
|
||||
<ToggleField
|
||||
label="Enable fast responses"
|
||||
checked={draft.enabled}
|
||||
onChange={(enabled) => setDraft((d) => ({ ...d, enabled }))}
|
||||
/>
|
||||
<div className="space-y-2">
|
||||
<ToggleField
|
||||
label="Allow company-sponsored fast responses"
|
||||
checked={draft.allowSponsored}
|
||||
onChange={(allowSponsored) =>
|
||||
setDraft((d) => ({ ...d, allowSponsored }))
|
||||
}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Covers accepted external messages from people without a linked
|
||||
Paperclip account.
|
||||
</p>
|
||||
</div>
|
||||
</fieldset>
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{!dirty &&
|
||||
result &&
|
||||
(result.status === "succeeded" ? (
|
||||
<div role="status" className="space-y-2 text-sm">
|
||||
<p>{result.text}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{(result.durationMs / 1000).toFixed(2)} seconds ·{" "}
|
||||
{result.usage.inputTokens ?? "—"} input /{" "}
|
||||
{result.usage.outputTokens ?? "—"} output tokens · Usage recorded
|
||||
in Costs.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{result.reason === "timeout"
|
||||
? "The model did not respond within three seconds. Try a faster model."
|
||||
: "Could not generate a response. Check the connection and model, then try again."}
|
||||
</p>
|
||||
))}
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="space-y-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onTest}
|
||||
disabled={dirty || !settings.enabled || saving || testing}
|
||||
>
|
||||
{testing ? "Testing…" : "Test response"}
|
||||
</Button>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{dirty
|
||||
? "Save changes before testing."
|
||||
: "Runs a small sample with an API charge."}
|
||||
</p>
|
||||
</div>
|
||||
{dirty && (
|
||||
<Button
|
||||
disabled={
|
||||
saving ||
|
||||
testing ||
|
||||
(draft.enabled &&
|
||||
(!draft.model || selected?.status !== "connected"))
|
||||
}
|
||||
onClick={() => onSave(draft)}
|
||||
>
|
||||
{saving ? "Saving…" : "Save fast response"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
export function FastResponseSettingsSection({
|
||||
companyId,
|
||||
}: {
|
||||
companyId: string;
|
||||
}) {
|
||||
const client = useQueryClient(),
|
||||
key = ["fast-response", companyId];
|
||||
const query = useQuery({
|
||||
queryKey: key,
|
||||
queryFn: () => fastResponsesApi.settings(companyId),
|
||||
});
|
||||
const [newlyConnectedId, setNewlyConnectedId] = useState<string | null>(null);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [provider, setProvider] = useState<AiProvider | null>(null);
|
||||
const [connectionId, setConnectionId] = useState<string | null>(null);
|
||||
const models = useQuery({
|
||||
queryKey: ["fast-response-models", companyId, connectionId],
|
||||
queryFn: () => fastResponsesApi.models(companyId, connectionId!),
|
||||
enabled: Boolean(connectionId),
|
||||
});
|
||||
const settingsRevision = JSON.stringify(
|
||||
query.data?.settings ?? { companyId },
|
||||
);
|
||||
const test = useMutation({
|
||||
mutationFn: (_revision: string) => fastResponsesApi.test(companyId),
|
||||
onSettled: () => {
|
||||
void client.invalidateQueries({
|
||||
queryKey: ["fast-response-history", companyId],
|
||||
});
|
||||
void client.invalidateQueries({
|
||||
predicate: (q) => String(q.queryKey[0]).includes("cost"),
|
||||
});
|
||||
},
|
||||
});
|
||||
const resetTest = test.reset;
|
||||
useEffect(() => {
|
||||
resetTest();
|
||||
}, [settingsRevision, resetTest]);
|
||||
const save = useMutation({
|
||||
mutationFn: (settings: UpdateFastResponse) =>
|
||||
fastResponsesApi.update(companyId, settings),
|
||||
onSuccess: (settings) => {
|
||||
test.reset();
|
||||
client.setQueryData(key, { ...query.data, settings });
|
||||
},
|
||||
});
|
||||
if (query.isPending)
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">Loading fast response…</p>
|
||||
);
|
||||
if (query.error)
|
||||
return (
|
||||
<div role="alert">
|
||||
<p className="text-sm text-destructive">
|
||||
Could not load fast response settings.
|
||||
</p>
|
||||
<Button variant="outline" onClick={() => void query.refetch()}>
|
||||
Try again
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
if (!query.data?.canManage || !query.data.settings) return null;
|
||||
return (
|
||||
<>
|
||||
<FastResponseSettingsView
|
||||
key={companyId}
|
||||
newlyConnectedId={newlyConnectedId}
|
||||
settings={query.data.settings}
|
||||
choices={query.data.choices}
|
||||
models={models.data}
|
||||
saving={save.isPending}
|
||||
testing={test.isPending}
|
||||
error={
|
||||
save.error?.message ??
|
||||
test.error?.message ??
|
||||
(models.error
|
||||
? "Could not load models. Enter a model ID or retry later."
|
||||
: null)
|
||||
}
|
||||
result={test.variables === settingsRevision ? test.data : null}
|
||||
onConnectionChange={setConnectionId}
|
||||
onSave={(v) => save.mutate(v)}
|
||||
onTest={() => test.mutate(settingsRevision)}
|
||||
onAdd={() => {
|
||||
setProvider(null);
|
||||
setAdding(true);
|
||||
}}
|
||||
/>
|
||||
<Dialog open={adding} onOpenChange={setAdding}>
|
||||
<DialogContent className="sm:max-w-2xl max-h-(--sz-85vh) overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add a fast response connection</DialogTitle>
|
||||
<DialogDescription>
|
||||
Use a shared API connection for short acknowledgements.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{provider ? (
|
||||
<ConnectionSetupFlow
|
||||
host="dialog"
|
||||
serviceSlug={provider}
|
||||
forceNewConnection
|
||||
aiConnection={{ provider, method: "api_key", mode: "shared" }}
|
||||
requiredAiOwnership="shared"
|
||||
onCancel={() => setAdding(false)}
|
||||
onComplete={async (result) => {
|
||||
const refreshed = await query.refetch();
|
||||
if (
|
||||
"connectionId" in result &&
|
||||
result.connectionId &&
|
||||
refreshed.data?.choices.some(
|
||||
(row) => row.id === result.connectionId,
|
||||
)
|
||||
)
|
||||
setNewlyConnectedId(result.connectionId);
|
||||
setAdding(false);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<ConnectionChoiceList
|
||||
choices={[
|
||||
"openrouter",
|
||||
"openai",
|
||||
"anthropic",
|
||||
"google",
|
||||
"xai",
|
||||
].map((id) => ({
|
||||
id,
|
||||
description: "Shared API connection",
|
||||
name:
|
||||
id === "openrouter"
|
||||
? "OpenRouter"
|
||||
: id === "openai"
|
||||
? "OpenAI"
|
||||
: id === "xai"
|
||||
? "xAI"
|
||||
: id === "google"
|
||||
? "Google"
|
||||
: "Anthropic",
|
||||
icon: <AppLogo name={id} brandKey={id} size={24} />,
|
||||
}))}
|
||||
onSelect={(id) => setProvider(id as AiProvider)}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -29,7 +29,7 @@ import { issuesApi } from "../../api/issues";
|
||||
import { useIssuePlanDocument } from "@/hooks/useIssuePlanDocument";
|
||||
import { useIssueDocuments } from "@/hooks/useIssueDocuments";
|
||||
import { useStreamlinedUiEnabled } from "@/hooks/useStreamlinedUiEnabled";
|
||||
import { selectAgentArtifactAttachments } from "@/lib/issue-artifacts";
|
||||
import { selectArtifactAttachments } from "@/lib/issue-artifacts";
|
||||
import { projectsApi } from "../../api/projects";
|
||||
import { useCompany } from "../../context/CompanyContext";
|
||||
import { useSidebar } from "../../context/SidebarContext";
|
||||
@@ -102,8 +102,6 @@ import { ExternalObjectRows } from "./external-object-rows";
|
||||
import {
|
||||
asRecord,
|
||||
compactRecord,
|
||||
defaultExecutionWorkspaceModeForProject,
|
||||
defaultProjectWorkspaceIdForProject,
|
||||
isMainIssueWorkspace,
|
||||
overrideLane,
|
||||
sortAdapterModels,
|
||||
@@ -321,12 +319,11 @@ export function IssueProperties({
|
||||
|| paneTabStandaloneDocuments.length > 0;
|
||||
// Artifacts covers the same three sources the tab body composes: work
|
||||
// products, documents (redundant with the Plan tab, intentionally), and
|
||||
// agent-created attachments. User comment uploads stay thread-only and
|
||||
// no longer summon the tab.
|
||||
// attachments from agents and people.
|
||||
const hasArtifactsTab =
|
||||
(paneTabWorkProducts?.length ?? 0) > 0
|
||||
|| paneTabStandaloneDocuments.length > 0
|
||||
|| selectAgentArtifactAttachments(paneTabAttachments, paneTabWorkProducts).length > 0;
|
||||
|| selectArtifactAttachments(paneTabAttachments, paneTabWorkProducts).length > 0;
|
||||
const [paneTab, setPaneTab] = useState<IssuePaneTab>("properties");
|
||||
const [closedPaneTabs, setClosedPaneTabs] = useState<Set<IssuePaneTab>>(() => new Set());
|
||||
// Once a plan document exists, surface it: switch the pane to the Plan tab so
|
||||
@@ -634,7 +631,7 @@ export function IssueProperties({
|
||||
onSuccess: (result, request) => {
|
||||
queryClient.setQueryData(queryKeys.executionWorkspaces.detail(result.workspace.id), result.workspace);
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(issue.id) });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.projects.detail(result.workspace.projectId) });
|
||||
if (result.workspace.projectId) void queryClient.invalidateQueries({ queryKey: queryKeys.projects.detail(result.workspace.projectId) });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.executionWorkspaces.overview(result.workspace.companyId) });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.executionWorkspaces.workspaceOperations(result.workspace.id) });
|
||||
if (companyId) {
|
||||
@@ -2008,26 +2005,7 @@ export function IssueProperties({
|
||||
option.id === (issue.projectId ?? "") && "bg-accent",
|
||||
)}
|
||||
onClick={() => {
|
||||
if (option.kind === "project") {
|
||||
const defaultMode = defaultExecutionWorkspaceModeForProject(option.project);
|
||||
onUpdate({
|
||||
projectId: option.project.id,
|
||||
projectWorkspaceId: defaultProjectWorkspaceIdForProject(option.project),
|
||||
executionWorkspaceId: null,
|
||||
executionWorkspacePreference: workspaceIsolationControlsVisible ? defaultMode : null,
|
||||
executionWorkspaceSettings: workspaceIsolationControlsVisible && option.project.executionWorkspacePolicy?.enabled
|
||||
? { mode: defaultMode }
|
||||
: null,
|
||||
});
|
||||
} else {
|
||||
onUpdate({
|
||||
projectId: null,
|
||||
projectWorkspaceId: null,
|
||||
executionWorkspaceId: null,
|
||||
executionWorkspacePreference: null,
|
||||
executionWorkspaceSettings: null,
|
||||
});
|
||||
}
|
||||
onUpdate({ projectId: option.kind === "project" ? option.project.id : null });
|
||||
setProjectOpen(false);
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { TextAttachmentContext } from "@/context/TextAttachmentContext";
|
||||
import { useContext, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { ArtifactUploadContent, type ArtifactUploadEntry } from "@/components/artifacts/ArtifactUploadControls";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type {
|
||||
AttachmentArtifactWorkProductMetadata,
|
||||
@@ -23,7 +24,7 @@ import { useIssueDocuments } from "@/hooks/useIssueDocuments";
|
||||
import { useIssueWorkProducts } from "@/hooks/useIssueWorkProducts";
|
||||
import {
|
||||
documentDisplayTitle,
|
||||
selectAgentArtifactAttachments,
|
||||
selectArtifactAttachments,
|
||||
} from "@/lib/issue-artifacts";
|
||||
import { DocumentCard } from "@/components/artifacts/RichArtifactCards";
|
||||
import {
|
||||
@@ -44,6 +45,7 @@ import { useLocation } from "@/lib/router";
|
||||
|
||||
interface IssuePropertiesArtifactsTabProps {
|
||||
issue: Issue;
|
||||
uploadState?: { entries: ArtifactUploadEntry[]; retry: (id: string) => void; dismiss: (id: string) => void };
|
||||
onOpenDocument?: (document: IssueDocument) => void;
|
||||
documentDeepLink?: {
|
||||
requestId: number;
|
||||
@@ -355,17 +357,16 @@ function DocumentRow({
|
||||
/**
|
||||
* Artifacts tab of the properties pane (PAP-491).
|
||||
*
|
||||
* A read-only "what did this task produce" view composed from three sources:
|
||||
* Task files and output composed from three sources:
|
||||
* work products, issue documents (also readable in the Plan tab — the
|
||||
* redundancy is intentional), and agent-created attachments. Attachments
|
||||
* already promoted to attachment-backed work products are deduped out, and
|
||||
* user uploads are excluded — those stay first-class in the conversation
|
||||
* thread.
|
||||
* redundancy is intentional), and attachments from agents and people.
|
||||
* Attachments already promoted to work products are deduped out.
|
||||
*/
|
||||
export function IssuePropertiesArtifactsTab({
|
||||
issue,
|
||||
documentDeepLink,
|
||||
onOpenDocument,
|
||||
uploadState,
|
||||
}: IssuePropertiesArtifactsTabProps) {
|
||||
const {
|
||||
data: attachments,
|
||||
@@ -406,7 +407,7 @@ export function IssuePropertiesArtifactsTab({
|
||||
const reviewDocsByKey = new Map(
|
||||
(documents ?? []).map((doc) => [doc.key, doc]),
|
||||
);
|
||||
const fileRows = selectAgentArtifactAttachments(attachments, workProducts);
|
||||
const fileRows = selectArtifactAttachments(attachments, workProducts);
|
||||
const runsById = useMemo(
|
||||
() => new Map((runs ?? []).map((run) => [run.runId, run])),
|
||||
[runs],
|
||||
@@ -513,21 +514,26 @@ export function IssuePropertiesArtifactsTab({
|
||||
</p>
|
||||
) : null;
|
||||
|
||||
const withUploads = (content: ReactNode, empty = false) => uploadState ? (
|
||||
<ArtifactUploadContent empty={empty} entries={uploadState.entries} onRetry={uploadState.retry} onDismiss={uploadState.dismiss}>{content}</ArtifactUploadContent>
|
||||
) : content;
|
||||
|
||||
if (
|
||||
workProductRows.length === 0 &&
|
||||
documentRows.length === 0 &&
|
||||
fileRows.length === 0
|
||||
) {
|
||||
if (feedback) return feedback;
|
||||
return (
|
||||
if (feedback) return withUploads(feedback);
|
||||
return withUploads(
|
||||
<div className="px-1 py-6 text-sm text-muted-foreground">
|
||||
No artifacts yet. Work products, documents, and agent-produced files
|
||||
will appear here.
|
||||
</div>
|
||||
</div>,
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
return withUploads(
|
||||
<div className="@container flex flex-col gap-3 py-2">
|
||||
{feedback}
|
||||
{groupedRows.map((group) => {
|
||||
|
||||
@@ -415,7 +415,7 @@ describe("markdown work product review row", () => {
|
||||
expect(container.querySelector("button[aria-expanded]")).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["image/png", "application/octet-stream"])("renders %s media tiles without duplicates or user uploads", async (contentType) => {
|
||||
it.each(["image/png", "application/octet-stream"])("renders %s media tiles with user uploads and without promoted duplicates", async (contentType) => {
|
||||
const image = { ...makeMarkdownAttachment(), contentType, originalFilename: "cover.png" };
|
||||
const looseImage = { ...image, id: "loose-image", contentPath: "/api/attachments/loose-image/content" };
|
||||
const video = { ...makeMarkdownAttachment(), id: "loose-video", contentType: "application/octet-stream", originalFilename: "clip.mp4", contentPath: "/api/attachments/loose-video/content" };
|
||||
@@ -427,11 +427,11 @@ describe("markdown work product review row", () => {
|
||||
await renderTab({}, "Cover artwork");
|
||||
await waitForAssertion(() => {
|
||||
const buttons = container.querySelectorAll('button[aria-label^="View image:"], button[aria-label^="Open video:"]');
|
||||
expect(buttons).toHaveLength(3);
|
||||
expect(buttons).toHaveLength(4);
|
||||
expect(container.querySelectorAll("img")).toHaveLength(2);
|
||||
expect(container.querySelectorAll("article")).toHaveLength(3);
|
||||
expect(container.querySelectorAll("article")).toHaveLength(4);
|
||||
expect(container.querySelector("video")?.getAttribute("src")).toBe(video.contentPath);
|
||||
expect(container.querySelectorAll("video")).toHaveLength(1);
|
||||
expect(container.querySelectorAll("video")).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ export function SidePanelFrame({
|
||||
data-maximized={maximized ? "true" : "false"}
|
||||
data-resizing={resizing ? "true" : "false"}
|
||||
className={cn(
|
||||
"flex min-h-0 min-w-0 flex-col overflow-hidden bg-(--side-panel-bg) text-(--side-panel-fg)",
|
||||
"relative flex min-h-0 min-w-0 flex-col overflow-hidden bg-(--side-panel-bg) text-(--side-panel-fg)",
|
||||
presentation === "docked" && "h-full border-l border-border",
|
||||
presentation === "sheet" && "h-full w-full",
|
||||
presentation === "embedded" && "h-full rounded-xl border border-border",
|
||||
|
||||
@@ -4,7 +4,8 @@ import type {
|
||||
} from "@paperclipai/shared";
|
||||
import { useCopyAction } from "@/lib/use-copy-action";
|
||||
import { IssueChatFeedbackButtons } from "@/components/AgentBubbleActionRow";
|
||||
import { Check, Copy, X } from "lucide-react";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { Check, Copy, X, Info } from "lucide-react";
|
||||
|
||||
/** Feedback-vote wiring for an agent bubble, resolved per comment by the host. */
|
||||
export interface TaskChatBubbleFeedback {
|
||||
@@ -28,8 +29,10 @@ export interface TaskChatBubbleFeedback {
|
||||
export function TaskChatBubbleActions({
|
||||
copyText,
|
||||
feedback,
|
||||
fastResponse,
|
||||
}: {
|
||||
copyText: string;
|
||||
fastResponse?: boolean;
|
||||
feedback?: TaskChatBubbleFeedback | null;
|
||||
}) {
|
||||
const { copied, failed, copy } = useCopyAction(2000);
|
||||
@@ -54,6 +57,7 @@ export function TaskChatBubbleActions({
|
||||
<Copy className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</button>
|
||||
{fastResponse && <Popover><PopoverTrigger asChild><button type="button" aria-label="Message details" title="Message details" className="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"><Info className="h-3.5 w-3.5" /></button></PopoverTrigger><PopoverContent className="text-xs">Platform-generated acknowledgement. The agent’s substantive response follows separately.</PopoverContent></Popover>}
|
||||
{feedback ? (
|
||||
<IssueChatFeedbackButtons
|
||||
activeVote={feedback.activeVote}
|
||||
|
||||
@@ -275,9 +275,11 @@ function targetLabel(
|
||||
) {
|
||||
const target = interaction.payload.target;
|
||||
if (!target) return null;
|
||||
const label =
|
||||
target.label ??
|
||||
(target.type === "issue_document" ? target.key : target.key);
|
||||
// A custom target key is a machine identifier for idempotency and stale
|
||||
// detection (e.g. `github:org/repo:pull:16`), not display copy. Only show a
|
||||
// custom target when the agent supplied a human label.
|
||||
if (target.type === "custom" && !target.label) return null;
|
||||
const label = target.label ?? target.key;
|
||||
const revision =
|
||||
target.revisionNumber == null ? null : `v${target.revisionNumber}`;
|
||||
return [label, revision].filter(Boolean).join(" · ");
|
||||
@@ -862,8 +864,8 @@ function ConfirmationCard({
|
||||
planDocument={planDocument}
|
||||
/>
|
||||
) : isPlanConfirmation && rejecting ? null : (
|
||||
<div className="flex flex-wrap items-start justify-between gap-2">
|
||||
<p className="min-w-0 flex-1 text-sm leading-5 text-foreground">
|
||||
<div className="space-y-2">
|
||||
<p className="whitespace-pre-line break-words text-sm leading-5 text-foreground">
|
||||
{isPlanConfirmation
|
||||
? "Do you accept this plan?"
|
||||
: interaction.payload.prompt}
|
||||
@@ -1152,8 +1154,8 @@ function CheckboxConfirmationCard({
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex flex-wrap items-start justify-between gap-2">
|
||||
<p className="min-w-0 flex-1 text-sm leading-5 text-foreground">
|
||||
<div className="space-y-2">
|
||||
<p className="whitespace-pre-line break-words text-sm leading-5 text-foreground">
|
||||
{interaction.payload.prompt}
|
||||
</p>
|
||||
<CompactTarget interaction={interaction} />
|
||||
|
||||
@@ -1701,6 +1701,25 @@ describe("TaskChatComposer", () => {
|
||||
).toBe("agent:a2");
|
||||
});
|
||||
|
||||
it("uses assignment suggestions and retains a manual human choice after refresh", async () => {
|
||||
const view = (suggestion: string) => <TaskChatComposer onAdd={vi.fn()} workMode="standard"
|
||||
enableReassign currentAssigneeValue="user:u1" suggestedAssigneeValue={suggestion}
|
||||
reassignOptions={[{ id: "agent:a1", label: "Alpha" }, { id: "agent:a2", label: "Beta" }, { id: "user:u1", label: "Me" }]}
|
||||
agentMap={new Map([["a1", { icon: "bot" }], ["a2", { icon: "bot" }]])} />;
|
||||
render(view("agent:a1"));
|
||||
const trigger = () => container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-assignee"]')!;
|
||||
expect(trigger().textContent).toContain("Alpha");
|
||||
flushSync(() => root!.render(view("agent:a2")));
|
||||
expect(trigger().textContent).toContain("Beta");
|
||||
flushSync(() => trigger().click());
|
||||
await flushAsync();
|
||||
const me = document.querySelector('[data-assignee-identity="user:u1"]')!.closest("button")!;
|
||||
flushSync(() => me.click());
|
||||
await flushAsync();
|
||||
flushSync(() => root!.render(view("agent:a1")));
|
||||
expect(trigger().textContent).toContain("Me");
|
||||
});
|
||||
|
||||
it("shows human avatars in assignee options and after selection", async () => {
|
||||
render(
|
||||
<TaskChatComposer
|
||||
|
||||
@@ -142,6 +142,7 @@ interface TaskChatComposerProps {
|
||||
{ label: string; image: string | null }
|
||||
> | null;
|
||||
currentAssigneeValue?: string;
|
||||
suggestedAssigneeValue?: string;
|
||||
onPendingAssigneeChange?: (value: string | null) => void;
|
||||
issueStatus?: string;
|
||||
/** Mobile document-flow host: 16px editor text so iOS doesn't zoom on focus. */
|
||||
@@ -397,6 +398,7 @@ export function TaskChatComposer({
|
||||
assigneeAdapterOverrides,
|
||||
userProfileMap,
|
||||
currentAssigneeValue = "",
|
||||
suggestedAssigneeValue,
|
||||
onPendingAssigneeChange,
|
||||
issueStatus,
|
||||
mobile = false,
|
||||
@@ -638,7 +640,7 @@ export function TaskChatComposer({
|
||||
const showAssignee = Boolean(
|
||||
enableReassign && reassignOptions && reassignOptions.length > 0,
|
||||
);
|
||||
const assigneeValue = creation ? currentAssigneeValue : pendingAssignee ?? currentAssigneeValue;
|
||||
const assigneeValue = creation ? currentAssigneeValue : pendingAssignee ?? suggestedAssigneeValue ?? currentAssigneeValue;
|
||||
const assigneeLabel =
|
||||
reassignOptions?.find((o) => o.id === assigneeValue)?.label ?? "Unassigned";
|
||||
const assigneeName =
|
||||
|
||||
@@ -370,6 +370,95 @@ describe("TaskChatInteractionCard", () => {
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("stacks the confirmation prompt full-width and hides unlabeled custom target keys", () => {
|
||||
const render = (target: RequestConfirmationInteraction["payload"]["target"]) =>
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<ThemeProvider>
|
||||
<TaskChatInteractionCard
|
||||
item={interactionItem(
|
||||
createRequestConfirmation({
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: "The change is open as PR #16.\n\nMay the PR merge?",
|
||||
target,
|
||||
},
|
||||
}),
|
||||
)}
|
||||
presentation="takeover"
|
||||
/>
|
||||
</ThemeProvider>
|
||||
</TooltipProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
render({ type: "custom", key: "github:paperclipai/paperclip-desktop:pull:16" });
|
||||
expect(container.textContent).not.toContain("github:paperclipai");
|
||||
const prompt = Array.from(container.querySelectorAll("p")).find((node) =>
|
||||
node.textContent?.startsWith("The change is open"),
|
||||
);
|
||||
expect(prompt?.className).not.toContain("flex-1");
|
||||
expect(prompt?.className).toContain("whitespace-pre-line");
|
||||
expect(prompt?.parentElement?.className).not.toContain("justify-between");
|
||||
|
||||
render({
|
||||
type: "custom",
|
||||
key: "github:paperclipai/paperclip-desktop:pull:16",
|
||||
label: "PR #16",
|
||||
href: "https://github.com/paperclipai/paperclip-desktop/pull/16",
|
||||
});
|
||||
const link = container.querySelector(
|
||||
'a[href="https://github.com/paperclipai/paperclip-desktop/pull/16"]',
|
||||
);
|
||||
expect(link?.textContent).toBe("PR #16");
|
||||
expect(container.textContent).not.toContain("github:paperclipai");
|
||||
});
|
||||
|
||||
it("stacks the checkbox confirmation prompt full-width and hides unlabeled custom target keys", () => {
|
||||
const render = (target: RequestConfirmationInteraction["payload"]["target"]) =>
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<ThemeProvider>
|
||||
<TaskChatInteractionCard
|
||||
item={interactionItem({
|
||||
...pendingRequestCheckboxConfirmationInteraction,
|
||||
payload: {
|
||||
...pendingRequestCheckboxConfirmationInteraction.payload,
|
||||
prompt: "Pick the drafts to delete.\n\nUnchecked drafts stay.",
|
||||
target,
|
||||
},
|
||||
})}
|
||||
presentation="takeover"
|
||||
/>
|
||||
</ThemeProvider>
|
||||
</TooltipProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
render({ type: "custom", key: "github:paperclipai/paperclip-desktop:pull:16" });
|
||||
expect(container.textContent).not.toContain("github:paperclipai");
|
||||
const prompt = Array.from(container.querySelectorAll("p")).find((node) =>
|
||||
node.textContent?.startsWith("Pick the drafts"),
|
||||
);
|
||||
expect(prompt?.className).not.toContain("flex-1");
|
||||
expect(prompt?.className).toContain("whitespace-pre-line");
|
||||
expect(prompt?.parentElement?.className).not.toContain("justify-between");
|
||||
|
||||
render({
|
||||
type: "custom",
|
||||
key: "github:paperclipai/paperclip-desktop:pull:16",
|
||||
label: "PR #16",
|
||||
href: "https://github.com/paperclipai/paperclip-desktop/pull/16",
|
||||
});
|
||||
const link = container.querySelector(
|
||||
'a[href="https://github.com/paperclipai/paperclip-desktop/pull/16"]',
|
||||
);
|
||||
expect(link?.textContent).toBe("PR #16");
|
||||
expect(container.textContent).not.toContain("github:paperclipai");
|
||||
});
|
||||
|
||||
it("keeps the plan revision in the header and hides the prompt while requesting changes", async () => {
|
||||
const interaction = createRequestConfirmation({
|
||||
sourceRunId: "run-plan",
|
||||
|
||||
@@ -328,12 +328,17 @@ describe("TaskChatProtocolCard", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("shows an unhealthy active runtime as unhealthy", () => {
|
||||
it.each([
|
||||
["active", "unhealthy", ["Unhealthy"], ["Running"]],
|
||||
["active", "unknown", [], ["Running", "Unhealthy"]],
|
||||
["open", "unhealthy", ["Unhealthy"], ["Running"]],
|
||||
["closed", "unhealthy", ["Stopped"], ["Unhealthy"]],
|
||||
] as const)("renders %s runtime with %s health", (status, healthStatus, visible, absent) => {
|
||||
const product = workProduct({
|
||||
type: "runtime_service",
|
||||
provider: "paperclip",
|
||||
status: "active",
|
||||
healthStatus: "unhealthy",
|
||||
status,
|
||||
healthStatus,
|
||||
title: "Storybook",
|
||||
metadata: { service: "storybook", port: 6006 },
|
||||
});
|
||||
@@ -343,85 +348,13 @@ describe("TaskChatProtocolCard", () => {
|
||||
surface: "resource",
|
||||
resourceKind: "deliverable",
|
||||
title: product.title,
|
||||
subtitle: "runtime service · active",
|
||||
subtitle: `runtime service · ${status}`,
|
||||
href: product.url,
|
||||
workProduct: product,
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain("Unhealthy");
|
||||
expect(container.textContent).not.toContain("Running");
|
||||
});
|
||||
|
||||
it("does not show running for an active runtime with unknown health", () => {
|
||||
const product = workProduct({
|
||||
type: "runtime_service",
|
||||
provider: "paperclip",
|
||||
status: "active",
|
||||
healthStatus: "unknown",
|
||||
title: "Storybook",
|
||||
metadata: { service: "storybook", port: 6006 },
|
||||
});
|
||||
renderCard(root, {
|
||||
id: "resource:deliverable:work-product-1",
|
||||
kind: "protocol",
|
||||
surface: "resource",
|
||||
resourceKind: "deliverable",
|
||||
title: product.title,
|
||||
subtitle: "runtime service · active",
|
||||
href: product.url,
|
||||
workProduct: product,
|
||||
});
|
||||
|
||||
expect(container.textContent).not.toContain("Running");
|
||||
expect(container.textContent).not.toContain("Unhealthy");
|
||||
});
|
||||
|
||||
it("shows an unhealthy runtime with a non-standard open status as unhealthy", () => {
|
||||
const product = workProduct({
|
||||
type: "runtime_service",
|
||||
provider: "paperclip",
|
||||
status: "open",
|
||||
healthStatus: "unhealthy",
|
||||
title: "Storybook",
|
||||
metadata: { service: "storybook", port: 6006 },
|
||||
});
|
||||
renderCard(root, {
|
||||
id: "resource:deliverable:work-product-1",
|
||||
kind: "protocol",
|
||||
surface: "resource",
|
||||
resourceKind: "deliverable",
|
||||
title: product.title,
|
||||
subtitle: "runtime service · open",
|
||||
href: product.url,
|
||||
workProduct: product,
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain("Unhealthy");
|
||||
expect(container.textContent).not.toContain("Running");
|
||||
});
|
||||
|
||||
it("shows a closed runtime as stopped even when its last health check failed", () => {
|
||||
const product = workProduct({
|
||||
type: "runtime_service",
|
||||
provider: "paperclip",
|
||||
status: "closed",
|
||||
healthStatus: "unhealthy",
|
||||
title: "Storybook",
|
||||
metadata: { service: "storybook", port: 6006 },
|
||||
});
|
||||
renderCard(root, {
|
||||
id: "resource:deliverable:work-product-1",
|
||||
kind: "protocol",
|
||||
surface: "resource",
|
||||
resourceKind: "deliverable",
|
||||
title: product.title,
|
||||
subtitle: "runtime service · closed",
|
||||
href: product.url,
|
||||
workProduct: product,
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain("Stopped");
|
||||
expect(container.textContent).not.toContain("Unhealthy");
|
||||
for (const label of visible) expect(container.textContent).toContain(label);
|
||||
for (const label of absent) expect(container.textContent).not.toContain(label);
|
||||
});
|
||||
|
||||
it("renders provider plan steps and status", () => {
|
||||
|
||||
@@ -135,6 +135,7 @@ export function commentsToTaskChatItems(
|
||||
} : {}),
|
||||
agent: effectiveAgentId(comment) ? ctx.agentMap?.get(effectiveAgentId(comment)!) ?? { id: effectiveAgentId(comment)! } : undefined,
|
||||
text: comment.body,
|
||||
origin: comment.origin ?? "comment",
|
||||
sourceChannel: kind === "human" ? comment.metadata?.sourceChannel : undefined,
|
||||
timestamp: formatTaskChatCommentTimestamp(comment, kind),
|
||||
optimistic,
|
||||
|
||||
@@ -101,6 +101,7 @@ export interface TaskChatTokenUsage {
|
||||
|
||||
/** A human/agent/system message bubble. */
|
||||
export interface TaskChatMessageItem {
|
||||
origin?: "comment" | "fast_response";
|
||||
/** Stable UI identity through optimistic acknowledgement; id remains canonical. */
|
||||
renderKey?: string;
|
||||
id: string;
|
||||
|
||||
@@ -2069,6 +2069,7 @@ export function attachSettledTurns(
|
||||
item.settled &&
|
||||
prev?.kind === "message" &&
|
||||
prev.author === "agent" &&
|
||||
prev.origin !== "fast_response" &&
|
||||
!prev.interstitial &&
|
||||
!prev.streaming &&
|
||||
prev.attachedTurn == null
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { IssueCreationSource } from "@paperclipai/shared";
|
||||
import { GitBranch } from "lucide-react";
|
||||
import {
|
||||
createIssueDetailPath,
|
||||
rememberIssueDetailLocationState,
|
||||
} from "@/lib/issueDetailBreadcrumb";
|
||||
import { Link } from "@/lib/router";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface IssueCreatedFromNoteProps {
|
||||
/** Access-checked creation provenance from the issue detail response. */
|
||||
createdFrom: IssueCreationSource | null | undefined;
|
||||
issueLinkState?: unknown;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* "Created from PAP-168 by Paperclip QA": the task a run was executing when it
|
||||
* created this one. Provenance only; it is not the structural parent and it is
|
||||
* not a blocker. Renders nothing when the viewer may not see the source.
|
||||
*/
|
||||
export function IssueCreatedFromNote({ createdFrom, issueLinkState, className }: IssueCreatedFromNoteProps) {
|
||||
if (!createdFrom) return null;
|
||||
const { issue, agent } = createdFrom;
|
||||
const ref = issue.identifier ?? issue.id;
|
||||
return (
|
||||
<p
|
||||
data-testid="issue-created-from"
|
||||
className={cn("flex min-w-0 items-center gap-1 text-xs text-muted-foreground", className)}
|
||||
>
|
||||
<GitBranch aria-hidden className="h-3 w-3 shrink-0" />
|
||||
<span className="shrink-0">Created from</span>
|
||||
<Link
|
||||
to={createIssueDetailPath(ref)}
|
||||
state={issueLinkState}
|
||||
onClickCapture={() => rememberIssueDetailLocationState(ref, issueLinkState)}
|
||||
className="min-w-0 truncate hover:text-foreground transition-colors"
|
||||
title={issue.title}
|
||||
>
|
||||
{issue.identifier ? `${issue.identifier} ${issue.title}` : issue.title}
|
||||
</Link>
|
||||
{agent && <span className="shrink-0">by {agent.name}</span>}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
@@ -98,4 +98,30 @@ describe("TaskDetailTasksPanel", () => {
|
||||
expect(retry).toHaveBeenCalledOnce();
|
||||
expect(container.querySelector('[data-task-id="child"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("shows the access-checked creation source even when the task has no parent", () => {
|
||||
render({
|
||||
createdFrom: {
|
||||
issue: { id: "source", identifier: "PAP-168", title: "Verify Tailscale fix", status: "in_progress" },
|
||||
run: { id: "run-1", agentId: "qa" },
|
||||
agent: { id: "qa", name: "Paperclip QA" },
|
||||
},
|
||||
subtasks: [], createdTasks: [], projects: [],
|
||||
});
|
||||
const group = container.querySelector('section[aria-label="Created from"]')!;
|
||||
expect(group).not.toBeNull();
|
||||
const note = group.querySelector('[data-testid="issue-created-from"]')!;
|
||||
expect(note.textContent).toContain("Created from");
|
||||
expect(note.textContent).toContain("PAP-168 Verify Tailscale fix");
|
||||
expect(note.textContent).toContain("by Paperclip QA");
|
||||
expect(note.querySelector('a')?.getAttribute("href")).toBe("/issues/PAP-168");
|
||||
expect(container.querySelector('section[aria-label="Ancestors"]')).toBeNull();
|
||||
expect(container.textContent).not.toContain("No tasks yet.");
|
||||
});
|
||||
|
||||
it("omits the creation source when the viewer may not see it", () => {
|
||||
render({ createdFrom: null, subtasks: [], createdTasks: [], projects: [] });
|
||||
expect(container.querySelector('section[aria-label="Created from"]')).toBeNull();
|
||||
expect(container.textContent).toContain("No tasks yet.");
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { issueStatusOrder } from "@/lib/issue-filters";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
||||
import { RelationNavigationList, TaskDetailSubtasksPanel, TaskDetailTaskList } from "./TaskDetailRelationsPanel";
|
||||
import { IssueCreatedFromNote } from "./IssueCreatedFromNote";
|
||||
|
||||
function TaskGroup({ name, projectPath, children }: { name: string; projectPath?: string; children: ReactNode }) {
|
||||
return (
|
||||
@@ -36,6 +37,8 @@ function TaskGroup({ name, projectPath, children }: { name: string; projectPath?
|
||||
export interface TaskDetailTasksPanelProps {
|
||||
/** API order: immediate parent first. Displayed root first. */
|
||||
ancestors?: NonNullable<Issue["ancestors"]>;
|
||||
/** Access-checked creation provenance; shown even when the source is not the parent. */
|
||||
createdFrom?: Issue["createdFrom"];
|
||||
subtasks: Issue[];
|
||||
createdTasks: Issue[];
|
||||
projects: Project[];
|
||||
@@ -45,7 +48,7 @@ export interface TaskDetailTasksPanelProps {
|
||||
issueLinkState?: unknown;
|
||||
}
|
||||
|
||||
export function TaskDetailTasksPanel({ ancestors = [], subtasks, createdTasks, projects, isLoading, hasError, onRetry, issueLinkState }: TaskDetailTasksPanelProps) {
|
||||
export function TaskDetailTasksPanel({ ancestors = [], createdFrom = null, subtasks, createdTasks, projects, isLoading, hasError, onRetry, issueLinkState }: TaskDetailTasksPanelProps) {
|
||||
const sortedSubtasks = sortTasks(subtasks);
|
||||
const groups = new Map<string, { name: string; path?: string; tasks: Issue[] }>();
|
||||
for (const item of sortTasks(createdTasks)) {
|
||||
@@ -63,6 +66,11 @@ export function TaskDetailTasksPanel({ ancestors = [], subtasks, createdTasks, p
|
||||
}
|
||||
return (
|
||||
<section className="flex flex-col gap-6" aria-label="Related tasks">
|
||||
{createdFrom && (
|
||||
<TaskGroup name="Created from">
|
||||
<IssueCreatedFromNote createdFrom={createdFrom} issueLinkState={issueLinkState} className="px-2 text-sm" />
|
||||
</TaskGroup>
|
||||
)}
|
||||
{ancestors.length > 0 && (
|
||||
<TaskGroup name="Ancestors">
|
||||
<RelationNavigationList
|
||||
@@ -90,7 +98,7 @@ export function TaskDetailTasksPanel({ ancestors = [], subtasks, createdTasks, p
|
||||
{onRetry && <Button variant="ghost" size="sm" onClick={onRetry}>Retry</Button>}
|
||||
</div>
|
||||
)}
|
||||
{!isLoading && !hasError && ancestors.length === 0 && subtasks.length === 0 && createdTasks.length === 0 && (
|
||||
{!isLoading && !hasError && !createdFrom && ancestors.length === 0 && subtasks.length === 0 && createdTasks.length === 0 && (
|
||||
<p className="py-6 text-center text-sm text-muted-foreground">No tasks yet.</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
@@ -37,6 +37,9 @@ import { WorkspaceFileBrowser } from "@/components/WorkspaceFileBrowser";
|
||||
import { AgentArtifactsPanel, AgentTasksPanel } from "@/components/chat/AgentWorkPanels";
|
||||
import { useAgentChatEnabled } from "@/hooks/useAgentChatEnabled";
|
||||
import { IssuePropertiesArtifactsTab } from "@/components/issue-properties/IssuePropertiesArtifactsTab";
|
||||
import { ArtifactDropzone } from "@/components/artifacts/ArtifactDropzone";
|
||||
import { ArtifactUploadButton } from "@/components/artifacts/ArtifactUploadControls";
|
||||
import { useIssueArtifactUploads } from "@/hooks/useIssueArtifactUploads";
|
||||
import { IssuePropertiesPlansTab } from "@/components/issue-properties/IssuePropertiesPlansTab";
|
||||
import { TaskDetailSubtasksPanel } from "@/components/task-detail/TaskDetailRelationsPanel";
|
||||
import {
|
||||
@@ -274,6 +277,7 @@ export function TaskSidePanel({
|
||||
const conversationAgentId = agentChatEnabled ? issue.conversationAgentId ?? null : null;
|
||||
const showRelatedTasks = showSubtasksTab && !conversationAgentId;
|
||||
const viewer = useTaskSidePanelFileRouting();
|
||||
const artifactUploads = useIssueArtifactUploads(issue);
|
||||
const { data: documentsData } = useIssueDocuments(issue.id);
|
||||
const documents = documentsData ?? EMPTY_ISSUE_DOCUMENTS;
|
||||
const { data: planDocument } = useIssuePlanDocument(issue.id);
|
||||
@@ -353,6 +357,7 @@ export function TaskSidePanel({
|
||||
}
|
||||
}, [openBrowserId, controller.activeTabId, onBrowserOpened, accountScope, issue.companyId, issue.id, fileTabsEnabled]);
|
||||
const activeTab = controller.tabs.find((tab) => tab.id === controller.activeTabId) ?? null;
|
||||
const canUploadArtifacts = activeTab?.payload.kind === "artifacts" && !conversationAgentId && !issue.id.startsWith("chat:");
|
||||
const subtasksAvailable = showRelatedTasks && (taskCount > 0 || tasksTab?.hasError === true);
|
||||
const hasSubtasksTab = controller.tabs.some((tab) => tab.id === "subtasks");
|
||||
|
||||
@@ -760,7 +765,7 @@ export function TaskSidePanel({
|
||||
markInteracted();
|
||||
controller.openTab(taskPanelAttachmentTab(id, title));
|
||||
if (viewer.state || viewer.browse) viewer.close();
|
||||
}}><IssuePropertiesArtifactsTab issue={issue} onOpenDocument={openDocument} /></TextAttachmentContext.Provider>;
|
||||
}}><IssuePropertiesArtifactsTab issue={issue} onOpenDocument={openDocument} uploadState={artifactUploads} /></TextAttachmentContext.Provider>;
|
||||
} else if (activeTab.payload.kind === "issue-document") {
|
||||
content = activeTab.payload.documentKey === "plan" ? (
|
||||
<IssuePropertiesPlansTab issue={issue} inline={inline} />
|
||||
@@ -815,11 +820,14 @@ export function TaskSidePanel({
|
||||
}
|
||||
|
||||
const contentMode = activeTab?.contentMode ?? "full-bleed";
|
||||
const header = <>{tabStrip}{canUploadArtifacts ? <ArtifactUploadButton onUpload={artifactUploads.upload} /> : null}</>;
|
||||
return (
|
||||
<ArtifactDropzone enabled={canUploadArtifacts} target={paneHeaderSlot?.closest<HTMLElement>("[data-presentation]")} onUpload={artifactUploads.upload}>
|
||||
<div className="flex h-full min-h-0 flex-col">
|
||||
{paneHeaderSlot ? createPortal(tabStrip, paneHeaderSlot) : (
|
||||
<span className="sr-only" role="status" aria-live="polite">{artifactUploads.announcement}</span>
|
||||
{paneHeaderSlot ? createPortal(header, paneHeaderSlot) : (
|
||||
<div className="flex h-(--side-panel-header-height) shrink-0 items-center gap-1 px-2">
|
||||
{tabStrip}
|
||||
{header}
|
||||
{onRequestClose ? (
|
||||
mobile ? (
|
||||
<Button variant="ghost" size="icon" className="size-(--sz-44px) shrink-0" aria-label="Close side panel" onClick={onRequestClose}>
|
||||
@@ -855,5 +863,6 @@ export function TaskSidePanel({
|
||||
) : content}
|
||||
</div>
|
||||
</div>
|
||||
</ArtifactDropzone>
|
||||
);
|
||||
}
|
||||
@@ -97,7 +97,7 @@ export function RadioCardGroup({
|
||||
const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (disabled) return;
|
||||
const idx = options.findIndex((option) => option.value === value);
|
||||
if (idx === -1) return;
|
||||
|
||||
let step: number | null = null;
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowRight") {
|
||||
step = 1;
|
||||
@@ -110,9 +110,11 @@ export function RadioCardGroup({
|
||||
// choice the viewer cannot make would select it.
|
||||
const len = options.length;
|
||||
for (let hop = 1; hop <= len; hop++) {
|
||||
const candidate = options[(((idx + step * hop) % len) + len) % len];
|
||||
const next = idx === -1 ? (step === 1 ? hop - 1 : len - hop) : (((idx + step * hop) % len) + len) % len;
|
||||
const candidate = options[next];
|
||||
if (!candidate.disabled) {
|
||||
onValueChange(candidate.value);
|
||||
event.currentTarget.querySelectorAll<HTMLButtonElement>('[role="radio"]')[next]?.focus();
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -135,7 +137,7 @@ export function RadioCardGroup({
|
||||
tooltip={option.tooltip}
|
||||
aria-label={option.accessibleLabel}
|
||||
disabled={disabled || option.disabled}
|
||||
tabIndex={option.value === value ? 0 : -1}
|
||||
tabIndex={option.value === value || (!options.some(item => item.value === value && !item.disabled) && option === options.find(item => !item.disabled)) ? 0 : -1}
|
||||
onClick={() => onValueChange(option.value)}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { SpekoCallHistory } from "./SpekoCallHistory";
|
||||
import { callHistoryFixture } from "../../../storybook/fixtures/spekoCallHistory";
|
||||
import { callHistoryFixture } from "../../../storybook/support/speko/spekoCallHistory";
|
||||
const mocks = vi.hoisted(() => ({list: vi.fn(), incoming: vi.fn(), end: vi.fn()}));
|
||||
vi.mock("@/api/voiceHistory", () => ({voiceHistoryApi: {list: mocks.list}}));
|
||||
vi.mock("@/api/voicePhone", () => ({voicePhoneApi: {history: mocks.incoming}}));
|
||||
|
||||
@@ -4,7 +4,7 @@ import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { TaskVoiceLauncher } from "./TaskVoiceLauncher";
|
||||
import { spekoEndpoint } from "../../../storybook/fixtures/spekoNative";
|
||||
import { spekoEndpoint } from "../../../storybook/support/speko/spekoNative";
|
||||
const mocks = vi.hoisted(() => ({ list: vi.fn() }));
|
||||
vi.mock("@/api/chatEndpoints", () => ({ chatEndpointsApi: { list: mocks.list } }));
|
||||
vi.mock("@/hooks/useChatConnectorsEnabled", () => ({ useChatConnectorsEnabled: () => ({ enabled: true }) }));
|
||||
|
||||
Reference in new issue
Block a user