Skip to content
Closed
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
5 changes: 5 additions & 0 deletions .changeset/paused-assistant-reopen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@sapiom/harness": patch
---

Bind Assistant requests to the current Studio lifecycle and restore newly started runtimes paused. Reopening Studio does not automatically recover earlier work; an explicit message enables execution. Include lifecycle changes in ordered Studio state updates and fence both managed engines during shutdown.
18 changes: 18 additions & 0 deletions packages/harness/src/core/assistant-lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,21 @@ it("keeps unresolved End durable across coordinator restart and global shutdown
await expect(coordinator.attach("studio-b", 0)).rejects.toThrow();
expect(ensure).not.toHaveBeenCalled();
});

it("rejects new attaches during shutdown while old association IO ignores cancellation", async () => {
const held = gate();
associate.mockImplementationOnce(async () => {
await held.promise;
return "ses_history";
});
const old = coordinator.attach("studio-a", 0);
const rejected = expect(old).rejects.toThrow();
await vi.waitFor(() => expect(associate).toHaveBeenCalledOnce());
coordinator.beginShutdown();
await expect(coordinator.attach("studio-a", 0)).rejects.toMatchObject({
failure: { code: "lifecycle_changed" },
});
expect(ensure).toHaveBeenCalledOnce();
held.release();
await rejected;
});
7 changes: 6 additions & 1 deletion packages/harness/src/core/assistant-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,11 @@ export class AssistantLifecycleCoordinator {
}

attach(id: string, expectedRevision: number): Promise<AssistantAttachment> {
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0)
if (
this.closed ||
!Number.isSafeInteger(expectedRevision) ||
expectedRevision < 0
)
return Promise.reject(failure("lifecycle_changed"));
const pending = this.pending.get(id);
if (pending)
Expand Down Expand Up @@ -305,6 +309,7 @@ export class AssistantLifecycleCoordinator {
beginShutdown(): void {
this.closed = true;
this.leases.clear();
this.pending.clear();
this.options.host.beginShutdown();
this.changed();
}
Expand Down
82 changes: 82 additions & 0 deletions packages/harness/src/core/assistant-state-projection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { expect, it, vi } from "vitest";
import type { AssistantLifecycle } from "../shared/assistant-session.js";
import {
parseAssistantState,
type AssistantStateSnapshot,
} from "../shared/assistant-state.js";
import { createAssistantStateProjection } from "./assistant-state-projection.js";

const state: AssistantLifecycle = {
version: 1,
harnessSessionId: "studio-a",
revision: 2,
lifecycle: "ended",
execution: "paused",
updatedAt: 10,
};
const runtime: AssistantStateSnapshot = {
hostInstanceId: "host-a",
authorityRevision: "grant-a",
revision: 45,
enabled: true,
sessions: [],
};
it("orders lifecycle-only updates with observations and clears disabled projections", () => {
let changedHost!: () => void, changedLifecycle!: () => void;
let native = runtime;
let rows = [state];
const stopHost = vi.fn(),
stopLifecycle = vi.fn(),
publish = vi.fn();
const projection = createAssistantStateProjection(
{
getAssistantState: () => native,
subscribeAssistantState: (fn) => {
changedHost = fn;
return stopHost;
},
},
{
snapshot: () => rows,
subscribe: (fn) => {
changedLifecycle = fn;
return stopLifecycle;
},
},
publish,
);
const initial = projection.get();
expect(parseAssistantState(initial)).toEqual(initial);
rows = [{ ...state, revision: 3, lifecycle: "open" }];
changedLifecycle();
const resumed = publish.mock.lastCall![0] as AssistantStateSnapshot;
expect(resumed.revision).toBeGreaterThan(initial.revision);
expect(resumed.lifecycles?.[0]?.lifecycle).toBe("open");
native = {
...native,
enabled: false,
authorityRevision: "grant-b",
revision: 46,
};
changedHost();
const revoked = publish.mock.lastCall![0] as AssistantStateSnapshot;
expect(revoked.revision).toBeGreaterThan(resumed.revision);
expect(revoked.lifecycles).toEqual([]);
expect(parseAssistantState(revoked)).toEqual(revoked);
projection.dispose();
expect(stopHost).toHaveBeenCalledOnce();
expect(stopLifecycle).toHaveBeenCalledOnce();
});
it.each([
[{ ...state, lease: "private" }],
[{ ...state, execution: "enabled" }],
[{ ...state, revision: -1 }],
[{ ...state, harnessSessionId: "../private" }],
[state, state],
null,
])(
"rejects malformed or contradictory lifecycle projection %j",
(lifecycles) => {
expect(parseAssistantState({ ...runtime, lifecycles })).toBeNull();
},
);
34 changes: 34 additions & 0 deletions packages/harness/src/core/assistant-state-projection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { AssistantStateSnapshot } from "../shared/assistant-state.js";
import type { AssistantLifecycleCoordinator } from "./assistant-lifecycle.js";
import type { OpenCodeHost } from "./opencode-host.js";

/** One ordering clock for runtime observations and durable lifecycle changes. */
export function createAssistantStateProjection(
host: Pick<OpenCodeHost, "getAssistantState" | "subscribeAssistantState">,
lifecycle: Pick<AssistantLifecycleCoordinator, "snapshot" | "subscribe">,
publish: (snapshot: AssistantStateSnapshot) => void,
) {
let revision = 0;
const get = (): AssistantStateSnapshot => {
// Reading access may synchronously revoke it and notify host subscribers.
const runtime = host.getAssistantState();
return {
...runtime,
revision,
lifecycles: runtime.enabled ? lifecycle.snapshot() : [],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Lifecycle projection has no consumer

The server publishes lifecycles, but the SPA never reads them. Mounted panes therefore cannot react to ordered lifecycle changes without another request.

Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

};
};
const changed = () => {
revision++;
publish(get());
};
const stopHost = host.subscribeAssistantState(changed);
const stopLifecycle = lifecycle.subscribe(changed);
return {
get,
dispose: () => {
stopHost();
stopLifecycle();
},
};
}
31 changes: 23 additions & 8 deletions packages/harness/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,8 @@ import {
import { IngestCredentialRegistry } from "../core/ingest-credentials.js";
import { AssistantAccess } from "../core/assistant-access.js";
import { AssistantSessionStore } from "../core/assistant-session-store.js";
import { AssistantLifecycleCoordinator } from "../core/assistant-lifecycle.js";
import { createAssistantStateProjection } from "../core/assistant-state-projection.js";
import { OpenCodeAssociations } from "../core/opencode-association.js";
import { OpenCodeHost, type HostedOpenCode } from "../core/opencode-host.js";
import { AssistantRecordStore } from "../core/assistant-record-store.js";
Expand Down Expand Up @@ -3566,10 +3568,15 @@ export const startServer = async (
stateRoot: statePaths.root,
authorize: authorizeAssistantWorkspace,
});
const getAssistantState = () => openCodeHost.getAssistantState();
const unsubscribeAssistant = openCodeHost.subscribeAssistantState(() =>
bus.publish({ type: "assistant.state", snapshot: getAssistantState() }),
const openCodeAssociations = new OpenCodeAssociations(assistantSessions);
const assistantLifecycle = new AssistantLifecycleCoordinator({ store: assistantSessions, host: openCodeHost, associations: openCodeAssociations });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Closed sessions retain Assistant runtimes

Closing a Studio session never calls assistantLifecycle.beginEnd, so its lease and native runtime remain active. An open pane can continue Assistant requests after closure.

Learn more

The lifecycle coordinator owns the fence that invalidates leases, retires the native Assistant process, and persists ending then ended. Production creates this coordinator but never invokes that flow for a Studio session close. The deletion route still calls sessionManager.close directly, while Assistant request admission only consults the coordinator lease and durable lifecycle. Closing the Terminal therefore leaves the Assistant process and lease usable.

Example: Alice opens Assistant, receives a lease, then closes the Studio tab. The DELETE request closes the Terminal, but the mounted pane can still send a leased Assistant request. The expected result is immediate rejection and retirement of both runtimes.

Recommended fix: Add one close orchestration boundary used by the REST deletion route. It must call assistantLifecycle.beginEnd(id) synchronously, join sessionManager.closeWithResult(id), Assistant retirement, and lifecycle persistence, then call assistantLifecycle.finishEnd(fence) only after the required cleanup result. Coalesce concurrent close callers through the complete operation as required by beginEnd.

Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

// Hydrate lifecycle headers without launching runtimes. A corrupt entry fails
// closed when selected rather than preventing unrelated sessions from loading.
await Promise.allSettled(sessionManager.list().map((session) => assistantLifecycle.describe(session.id)));
const assistantProjection = createAssistantStateProjection(openCodeHost, assistantLifecycle, (snapshot) =>
bus.publish({ type: "assistant.state", snapshot }),
);
const getAssistantState = assistantProjection.get;
const app: Express = express();
app.disable("x-powered-by");
app.use("/opencode-runtime", openCodeBridge.router);
Expand All @@ -3585,8 +3592,12 @@ export const startServer = async (
getEnvironment: () => assistantAccess.get()?.environment ?? null,
loadSystemPrompt: options.loadSystemPrompt,
}),
new OpenCodeAssociations(assistantSessions),
new OpenCodeFinalResponse({ onPersisted: async (hosted) => { await recordCaptures.get(hosted)?.checkpoint(); } }),
openCodeAssociations,
new OpenCodeFinalResponse({
assertCurrent: (hosted) => assistantLifecycle.assertRuntime(hosted, true),
onPersisted: async (hosted) => { await recordCaptures.get(hosted)?.checkpoint(); },
}),
assistantLifecycle,
),
);

Expand Down Expand Up @@ -4321,11 +4332,14 @@ export const startServer = async (

credentialStoreObserver?.close();
unsubscribeCredentialChanges();
// Fence both engines synchronously. Native ownership cleanup can wait on
// process proof and must not leave Terminal admission open during that wait.
assistantLifecycle.beginShutdown();
sessionManager.beginShutdown();
assistantAccess.close();
await settle(() => openCodeHost.close());
unsubscribeAssistant();
const nativeClosing = settle(() => openCodeHost.close());
assistantProjection.dispose();
openCodeBridge.close();
await settle(() => sessionManager.beginShutdown());
const bootstrapClosing = settle(() => projectBootstrap?.close());
const registrationClosing = settle(() => createdAgentRegistration.close());
coordinatorActive = false;
Expand Down Expand Up @@ -4353,6 +4367,7 @@ export const startServer = async (
// socket if an adapter misses its own exit acknowledgement.
const SHUTDOWN_KILL_TIMEOUT_MS = 5_000;
const killsSettled = Promise.all([
nativeClosing,
settle(() => sessionManager.killAll()),
settle(() => taskManager.killAll()),
]).then(() => {});
Expand Down
33 changes: 33 additions & 0 deletions packages/harness/src/shared/assistant-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,36 @@ export interface AssistantSessionView extends Omit<
history: "available" | "partial" | "missing" | "unavailable";
nativeResume: "unchecked" | "available" | "missing" | "unavailable";
}

/** Strict public lifecycle decoding; a descriptor never carries execution credentials. */
export function parseAssistantLifecycle(
value: unknown,
): AssistantLifecycle | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const row = value as Record<string, unknown>;
if (
Object.keys(row).some(
(key) =>
![
"version",
"harnessSessionId",
"revision",
"lifecycle",
"execution",
"updatedAt",
].includes(key),
) ||
row.version !== 1 ||
typeof row.harnessSessionId !== "string" ||
!/^[A-Za-z0-9_-]{1,256}$/.test(row.harnessSessionId) ||
!Number.isSafeInteger(row.revision) ||
(row.revision as number) < 0 ||
!Number.isSafeInteger(row.updatedAt) ||
(row.updatedAt as number) < 0 ||
!["open", "ending", "ended"].includes(row.lifecycle as string) ||
!["enabled", "paused"].includes(row.execution as string) ||
(row.lifecycle !== "open" && row.execution !== "paused")
)
return null;
return { ...row } as unknown as AssistantLifecycle;
}
22 changes: 22 additions & 0 deletions packages/harness/src/shared/assistant-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import {
parseOpenCodeTransportFailure,
type OpenCodeTransportFailure,
} from "./opencode-errors.js";
import {
parseAssistantLifecycle,
type AssistantLifecycle,
} from "./assistant-session.js";

export interface AssistantSessionSummary {
harnessSessionId: string;
Expand All @@ -18,6 +22,7 @@ export interface AssistantStateSnapshot {
revision: number;
enabled: boolean;
sessions: readonly AssistantSessionSummary[];
lifecycles?: readonly AssistantLifecycle[];
}
export type AssistantObservation = Omit<
AssistantSessionSummary,
Expand Down Expand Up @@ -53,6 +58,7 @@ export function parseAssistantState(
"revision",
"enabled",
"sessions",
"lifecycles",
]);
if (
!input ||
Expand Down Expand Up @@ -110,11 +116,27 @@ export function parseAssistantState(
...(failure ? { failure } : {}),
});
}
const lifecycles: AssistantLifecycle[] = [];
if (input.lifecycles !== undefined) {
if (
!Array.isArray(input.lifecycles) ||
(!input.enabled && input.lifecycles.length)
)
return null;
const identities = new Set<string>();
for (const raw of input.lifecycles) {
const lifecycle = parseAssistantLifecycle(raw);
if (!lifecycle || identities.has(lifecycle.harnessSessionId)) return null;
identities.add(lifecycle.harnessSessionId);
lifecycles.push(lifecycle);
}
}
return {
hostInstanceId: input.hostInstanceId,
authorityRevision: input.authorityRevision,
revision: input.revision,
enabled: input.enabled,
sessions,
...(input.lifecycles !== undefined ? { lifecycles } : {}),
};
}
Loading
Loading