Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion apps/factory/agent/channels/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,11 @@ export default defineChannel<
headers: { "cache-control": "no-store" }
});
} catch (error) {
await failWorkspace(id, "Could not start the Eve workspace session.");
const reason =
error instanceof Error && error.message.trim()
? `Could not start the workspace session: ${error.message.trim()}`
: "Could not start the workspace session.";
await failWorkspace(id, reason);
throw error;
}
})
Expand Down
118 changes: 95 additions & 23 deletions apps/factory/app/workspace-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@ import {
import { sandboxSshCommand } from "../agent/lib/sandbox-ssh";
import { CopyCommand } from "../components/copy-command";
import { Button } from "../components/ui/button";
import type { PublicWorkspace } from "./workspace-types";
import {
latestWorkspaceFailure,
type PublicWorkspace,
type WorkspaceFailure
} from "./workspace-types";

const CONSOLE_HEADERS = { [OPERATOR_ACTION_HEADER]: OPERATOR_SESSION_ACTION };
const streamdownPlugins: PluginConfig = {
Expand Down Expand Up @@ -123,14 +127,34 @@ export function WorkspaceClient({ workspaceId }: WorkspaceClientProps) {
</p>
</main>
);
if (!loaded?.workspace.sessionId)
if (!loaded)
return (
<main className="grid min-h-[60vh] place-items-center" id="main-content">
<p className="shimmer-text text-sm" role="status">
Loading durable Eve session…
</p>
</main>
);
if (!loaded.workspace.sessionId)
return (
<main className="grid min-h-[60vh] place-items-center" id="main-content">
{loaded.workspace.error ? (
<div
className="mx-4 max-w-2xl rounded-md border border-destructive/20 bg-destructive/10 px-4 py-3 text-sm text-destructive"
role="alert"
>
<p className="font-medium">Workspace failed to start</p>
<p className="mt-1 whitespace-pre-wrap text-foreground">
{loaded.workspace.error}
</p>
</div>
) : (
<p className="shimmer-text text-sm" role="status">
Starting workspace session…
</p>
)}
</main>
);
return (
<WorkspaceChat initialEvents={loaded.events} workspace={loaded.workspace} />
);
Expand Down Expand Up @@ -202,6 +226,12 @@ function WorkspaceChat({
const busy =
serverBusy || agent.status === "submitted" || agent.status === "streaming";
const hasAssistantProgress = hasRenderableAssistantProgress(messages.at(-1));
const streamedFailure = useMemo(
() => latestWorkspaceFailure(events),
[events]
);
const failure =
streamedFailure ?? fallbackWorkspaceFailure(agent.error?.message);

useEffect(() => {
if (
Expand Down Expand Up @@ -270,11 +300,11 @@ function WorkspaceChat({
</div>
<div className="flex shrink-0 items-center gap-3 pt-1">
<span
className={`flex items-center gap-1.5 text-xs ${agent.status === "error" ? "text-destructive" : busy ? "text-muted-foreground" : "text-success"}`}
className={`flex items-center gap-1.5 text-xs ${failure ? "text-destructive" : busy ? "text-muted-foreground" : "text-success"}`}
role="status"
>
{busy ? <Loader2Icon className="size-3 animate-spin" /> : null}
{busy ? "Working" : agent.status === "error" ? "Error" : "Ready"}
{busy ? "Working" : failure ? "Error" : "Ready"}
</span>
<details className="relative">
<summary className="cursor-pointer list-none rounded-md border border-border px-2 py-1 text-xs text-muted-foreground hover:text-foreground">
Expand Down Expand Up @@ -328,15 +358,7 @@ function WorkspaceChat({
</ChatConversation>

<div className="shrink-0 bg-background px-6 pt-2 pb-5 max-[520px]:px-4">
{agent.error ? (
<div
className="mx-auto mb-2 flex max-w-3xl items-start gap-2 rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive"
role="alert"
>
<CircleAlertIcon className="mt-0.5 size-3.5 shrink-0" />
{agent.error.message}
</div>
) : null}
{failure ? <WorkspaceFailureAlert failure={failure} /> : null}
<ChatComposer
busy={busy}
disabled={busy}
Expand All @@ -351,6 +373,32 @@ function WorkspaceChat({
);
}

function WorkspaceFailureAlert({
failure
}: {
readonly failure: WorkspaceFailure;
}) {
return (
<div
className="mx-auto mb-2 flex max-w-3xl items-start gap-2 rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2.5 text-xs text-destructive"
role="alert"
>
<CircleAlertIcon className="mt-0.5 size-3.5 shrink-0" />
<div className="min-w-0 space-y-1.5">
<p className="font-medium">{failureHeadline(failure)}</p>
{failure.hint ? (
<p className="whitespace-pre-wrap text-foreground">{failure.hint}</p>
) : null}
{failure.detail ? (
<pre className="max-h-48 overflow-auto whitespace-pre-wrap rounded bg-background/70 p-2 font-mono text-[11px] leading-5 text-foreground">
{failure.detail}
</pre>
) : null}
</div>
</div>
);
}

function ChatConversation({
children
}: {
Expand Down Expand Up @@ -746,7 +794,9 @@ function ActivityFeed({
>
{new Date(event.meta.at).toLocaleTimeString()}
</time>
<span className="min-w-0 truncate">{event.type}</span>
<span className="min-w-0 truncate">
{describeActivityEvent(event)}
</span>
</li>
))}
</ol>
Expand Down Expand Up @@ -803,15 +853,18 @@ function appendOptimisticMessage(
}

function hasLatestUserMessage(messages: readonly EveMessage[], text: string) {
return (
[...messages]
.reverse()
.find((message) => message.role === "user")
?.parts.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n")
.trim() === text.trim()
);
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (message?.role !== "user") continue;
return (
message.parts
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n")
.trim() === text.trim()
);
}
return false;
}

function hasRenderableAssistantProgress(message: EveMessage | undefined) {
Expand Down Expand Up @@ -856,3 +909,22 @@ function partKey(part: EveMessagePart, index: number) {
? part.toolCallId
: `${part.type}:${index}`;
}

function fallbackWorkspaceFailure(
message: string | undefined
): WorkspaceFailure | undefined {
const normalized = message?.trim();
return normalized ? { message: normalized } : undefined;
}

function failureHeadline(failure: WorkspaceFailure): string {
const { code, message } = failure;
return !code || message === code || message.startsWith(`${code}:`)
? message
: `${code}: ${message}`;
}

function describeActivityEvent(event: MessageStreamEvent): string {
const failure = latestWorkspaceFailure([event]);
return failure ? `${event.type} — ${failureHeadline(failure)}` : event.type;
}
71 changes: 71 additions & 0 deletions apps/factory/app/workspace-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,74 @@ export function workspaceStatusLabel(status: string): string {
if (status === "error") return "Error";
return status;
}

export interface WorkspaceFailure {
readonly code?: string;
readonly detail?: string;
readonly hint?: string;
readonly message: string;
}

type WorkspaceEvent = {
readonly data?: unknown;
readonly type: string;
};

const FAILURE_EVENTS = new Set([
"step.failed",
"turn.failed",
"session.failed"
]);
const FAILURE_RESET_EVENTS = new Set([
"turn.started",
"turn.completed",
"turn.cancelled",
"session.completed"
]);

/**
* Projects the current run failure from an agent event stream. Keeping this
* boundary independent of Eve's event types lets another harness map its
* failures into the workspace UI without changing the presentation.
*/
export function latestWorkspaceFailure(
events: readonly WorkspaceEvent[]
): WorkspaceFailure | undefined {
let failure: WorkspaceFailure | undefined;
for (const event of events) {
if (FAILURE_RESET_EVENTS.has(event.type)) {
failure = undefined;
continue;
}
if (!FAILURE_EVENTS.has(event.type)) continue;
const candidate = workspaceFailureFrom(event.data);
if (candidate) failure = candidate;
}
return failure;
}

function workspaceFailureFrom(data: unknown): WorkspaceFailure | undefined {
if (!isRecord(data) || typeof data.message !== "string") return undefined;
const message = data.message.trim();
if (!message) return undefined;
const details = isRecord(data.details) ? data.details : undefined;
const code = nonEmptyString(data.code);
const hint = nonEmptyString(details?.hint);
const rawDetail = nonEmptyString(details?.detail);
return {
...(code ? { code } : {}),
...(rawDetail && rawDetail !== message ? { detail: rawDetail } : {}),
...(hint ? { hint } : {}),
message
};
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

function nonEmptyString(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
const normalized = value.trim();
return normalized || undefined;
}
57 changes: 57 additions & 0 deletions apps/factory/tests/workspace-types.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import test from "node:test";

import {
isWorkspaceRunning,
latestWorkspaceFailure,
workspaceStatusLabel
} from "../app/workspace-types.ts";

Expand All @@ -14,3 +15,59 @@ test("workspace status labels describe operator-visible state", () => {
assert.equal(isWorkspaceRunning("running"), true);
assert.equal(isWorkspaceRunning("idle"), false);
});

test("projects actionable failure information from workspace events", () => {
const events = [
{ type: "turn.started", data: { turnId: "turn_1" } },
{
type: "step.failed",
data: {
code: "gateway-auth",
message: "Failed",
details: {
hint: "Refresh the AI Gateway credentials.",
detail: "401 Unauthorized\nCaused by an expired token."
}
}
},
{
type: "turn.failed",
data: {
code: "gateway-auth",
message: "Failed",
details: {
hint: "Refresh the AI Gateway credentials.",
detail: "401 Unauthorized\nCaused by an expired token."
}
}
}
];
assert.deepEqual(latestWorkspaceFailure(events), {
code: "gateway-auth",
message: "Failed",
hint: "Refresh the AI Gateway credentials.",
detail: "401 Unauthorized\nCaused by an expired token."
});
});

test("clears an old workspace failure when a later turn starts", () => {
assert.equal(
latestWorkspaceFailure([
{
type: "session.failed",
data: { code: "failed", message: "First run failed" }
},
{ type: "turn.started", data: { turnId: "turn_2" } }
]),
undefined
);
});

test("ignores malformed workspace failure events", () => {
assert.equal(
latestWorkspaceFailure([
{ type: "turn.failed", data: { code: "failed", message: " " } }
]),
undefined
);
});
Loading