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
55 changes: 55 additions & 0 deletions backend/__tests__/service/hosted-stopped-roster.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const express = require('express');
const request = require('supertest');
const jwt = require('jsonwebtoken');
const { setupMongoDb, closeMongoDb } = require('../utils/testUtils');
const User = require('../../models/User');
const Pod = require('../../models/Pod');
const { AgentInstallation } = require('../../models/AgentRegistry');
const hosted = require('../../routes/hosted');
const podAgents = require('../../routes/registry/pod-agents');

const SECRET = 'hosted-stopped-roster-test';

describe('a hosted agent stopped through the route', () => {
let app; let owner; let pod; let auth;

beforeAll(async () => {
process.env.JWT_SECRET = SECRET;
process.env.HOSTED_ENGINE = 'native';
process.env.LITELLM_BASE_URL = 'http://litellm.test';
process.env.LITELLM_API_KEY = 'test-key';
await setupMongoDb();
app = express();
app.use(express.json());
app.use('/api/hosted', hosted.default || hosted);
app.use('/api/registry', podAgents.default || podAgents);
owner = await User.create({ username: 'stop-owner', email: 'stop-owner@test.com', password: 'password1' });
pod = await Pod.create({ name: 'Stop pod', type: 'chat', createdBy: owner._id, members: [owner._id] });
auth = { Authorization: `Bearer ${jwt.sign({ id: String(owner._id) }, SECRET)}` };
await AgentInstallation.create({
agentName: 'stop-agent', instanceId: 'default', podId: pod._id, version: '1', installedBy: owner._id,
config: new Map([['runtime', { runtimeType: 'hosted' }], ['hosted', { engine: 'native', provisionedAt: new Date() }]]),
});
});

afterAll(async () => {
delete process.env.HOSTED_ENGINE;
delete process.env.LITELLM_BASE_URL;
delete process.env.LITELLM_API_KEY;
await closeMongoDb();
});

const rosterConnection = async () => {
const res = await request(app).get(`/api/registry/pods/${pod._id}/agents`).set(auth);
expect(res.status).toBe(200);
return res.body.agents.find((row) => row.name === 'stop-agent').connection;
};

it('reads as stopped on the roster, because the stop writes what the roster reads', async () => {
expect(await rosterConnection()).toEqual({ state: 'available', lastSeenAt: null });
const stopped = await request(app).post('/api/hosted/deprovision').set(auth)
.send({ agentName: 'stop-agent', instanceId: 'default' });
expect(stopped.status).toBe(200);
expect(await rosterConnection()).toEqual({ state: 'stopped', lastSeenAt: null });
});
});
28 changes: 28 additions & 0 deletions backend/__tests__/service/registry.add-agent-to-pod.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ const DMService = require('../../services/dmService');
const pgMirrorWrite = require('../../services/pgMirrorWrite');
const { previewInstallNarrowing } = require('../../services/outsiderGrantNarrowingPreview');
const { assertAgentRuntimeMayJoinPod } = require('../../services/outsiderGrantAgentJoinPolicy');
const AgentMessageService = require('../../services/agentMessageService');
const HostedEngine = require('../../services/hostedEngine');
const registryRoutes = require('../../routes/registry');

const SECRET = 'add-agent-to-pod-test';
Expand Down Expand Up @@ -595,6 +597,32 @@ describe('adding an existing agent to another pod', () => {
expect((await row(target._id)).config.hosted.provisionedAt).toBeNull();
});

it('carries the stop into the new pod and posts no intro there', async () => {
await installHosted();
const stoppedAt = new Date('2026-11-06T12:00:00Z');
await AgentInstallation.updateOne({ podId: home._id }, {
$set: { 'config.hosted.provisionedAt': null, 'config.hosted.deprovisionedAt': stoppedAt },
});
const post = jest.spyOn(AgentMessageService, 'postMessage').mockResolvedValue({});
try {
expect((await add(owner, target._id)).status).toBe(200);
const added = await row(target._id);
expect(new Date(added.config.hosted.deprovisionedAt)).toEqual(stoppedAt);
expect(HostedEngine.hostedIsStopped(added)).toBe(true);
expect(post).not.toHaveBeenCalled();
} finally {
post.mockRestore();
}
});

it('has no stop to carry when it is running, and still counts as running', async () => {
await installHosted();
expect((await add(owner, target._id)).status).toBe(200);
const added = await row(target._id);
expect(added.config.hosted.deprovisionedAt).toBeUndefined();
expect(HostedEngine.hostedIsStopped(added)).toBe(false);
});

it('stays on the Durable Object when that is where it runs', async () => {
await installHosted();
await AgentInstallation.updateOne({ podId: home._id }, { $unset: { 'config.hosted': 1 } });
Expand Down
43 changes: 43 additions & 0 deletions backend/__tests__/unit/routes/registry.pod-agents-activity.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,28 @@ describe('pod agents lastActiveAt derivation (#915)', () => {
expect(res.body.agents[0].connection.state).toBe('revoked');
});

it('does not call a daemon seat stopped because a hosted row of the identity was', async () => {
AgentInstallation.getInstalledAgents.mockResolvedValue([baseInstallation({
agentName: 'local',
config: new Map([
['runtime', { runtimeType: 'hosted' }],
['hosted', { provisionedAt: null, deprovisionedAt: new Date() }],
]),
})]);
User.find.mockReturnValue({ select: jest.fn().mockReturnValue({ lean: jest.fn().mockResolvedValue([{
_id: 'bot-1', username: 'local-default', botMetadata: { machineId: 'machine-1' }, agentRuntimeTokens: [],
}]) }) });
AgentCredential.find.mockReturnValue({ select: jest.fn().mockReturnValue({ lean: jest.fn().mockResolvedValue([
{ kind: 'daemon', machineId: 'machine-1', status: 'active' },
]) }) });
Machine.find.mockReturnValue({ select: jest.fn().mockReturnValue({ lean: jest.fn().mockResolvedValue([{
machineId: 'machine-1', lastSeenAt: new Date(),
}]) }) });
const res = await request(app).get(`/api/registry/pods/${POD_ID}/agents`);
expect(res.status).toBe(200);
expect(res.body.agents[0].connection.state).not.toBe('stopped');
});

it('projects a running daemon-bound wrapper from its live machine and active seat key', async () => {
AgentInstallation.getInstalledAgents.mockResolvedValue([baseInstallation({
agentName: 'local', config: new Map([['runtime', { runtimeType: 'wrapper' }]]),
Expand Down Expand Up @@ -300,6 +322,27 @@ describe('pod agents lastActiveAt derivation (#915)', () => {
expect(res.body.agents[0].connection).toEqual({ state: 'available', lastSeenAt: null });
});

it.each([['native', { engine: 'native' }], ['durable object', {}]])('says a hosted seat its owner stopped is stopped (%s engine)', async (_label, engine) => {
AgentInstallation.getInstalledAgents.mockResolvedValue([baseInstallation({
config: new Map([
['runtime', { runtimeType: 'hosted' }],
['hosted', { ...engine, provisionedAt: null, deprovisionedAt: new Date() }],
]),
})]);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const res = await request(app).get(`/api/registry/pods/${POD_ID}/agents`);
expect(res.status).toBe(200);
expect(res.body.agents[0].connection).toEqual({ state: 'stopped', lastSeenAt: null });
});

it('leaves a hosted seat that was never started without a connection', async () => {
AgentInstallation.getInstalledAgents.mockResolvedValue([baseInstallation({
config: new Map([['runtime', { runtimeType: 'hosted' }], ['hosted', { engine: 'native', provisionedAt: null }]]),
})]);
const res = await request(app).get(`/api/registry/pods/${POD_ID}/agents`);
expect(res.status).toBe(200);
expect(res.body.agents[0].connection).toBeUndefined();
});

it('shows a provisioned native-engine hosted seat as available without a runtime token', async () => {
AgentInstallation.getInstalledAgents.mockResolvedValue([baseInstallation({
config: new Map([
Expand Down
3 changes: 2 additions & 1 deletion backend/routes/hosted.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,8 @@ router.post('/provision', hostedRateLimit, auth, async (req: any, res: any) => {
/**
* POST /api/hosted/deprovision { agentName, instanceId? }
* Stops the runtime. The installation and identity stay — ADR-001 §3 identity
* continuity; re-provisioning finds the same memory. The token does NOT
* continuity. A native-engine agent loses nothing. The Durable Object engine
* deletes its storage, conversation transcript included. The token does NOT
Comment thread
lilyshen0722 marked this conversation as resolved.
Resolved
* survive: it is revoked here, and provision mints a fresh one.
*/
router.post('/deprovision', hostedRateLimit, auth, async (req: any, res: any) => {
Expand Down
9 changes: 7 additions & 2 deletions backend/routes/registry/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -736,7 +736,10 @@ const installAgent = async (req: any, res: any, addition?: { alreadyInPod: Recor
),
// Started and stopped are the agent's state, not one room's: a
// stopped agent added to another pod stays stopped there too.
...(heldHostedRow ? { provisionedAt: held.provisionedAt ?? null } : {}),
...(heldHostedRow ? {
provisionedAt: held.provisionedAt ?? null,
...(held.deprovisionedAt ? { deprovisionedAt: held.deprovisionedAt } : {}),
} : {}),
};
}
}
Expand Down Expand Up @@ -1084,7 +1087,9 @@ const installAgent = async (req: any, res: any, addition?: { alreadyInPod: Recor
&& podDoc.type !== 'dm'
&& podDoc.type !== 'agent-room'
&& ((podDoc.members?.length || 0) >= 2 || isOwnWorkspace)
&& !(greetsItself && firstContactFired);
&& !(greetsItself && firstContactFired)
// A stopped agent can't answer the "ping me" the intro ends on.
&& !HostedEngine.hostedIsStopped(installation);
if (introWorthy) {
// Task #62 follow-up: the intro post passes `displayName` to
// AgentMessageService.postMessage, which forwards it to
Expand Down
8 changes: 7 additions & 1 deletion backend/routes/registry/pod-agents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const AgentTemplate = require('../../models/AgentTemplate');
const AgentCredential = require('../../models/AgentCredential');
const Machine = require('../../models/Machine');
const { deriveAgentConnection } = require('../../services/agentConnectionStateService');
const { hostedRunsNative } = require('../../services/hostedEngine');
const { hostedRunsNative, readHostedConfig } = require('../../services/hostedEngine');
const { retireHostedRoomRows } = require('../../services/hostedRuntimeService');
const { retireDmRowsWithAgent } = require('../../services/agentDmRowService');
const Pod = require('../../models/Pod');
Expand Down Expand Up @@ -467,6 +467,12 @@ podAgentsRouter.get('/pods/:podId/agents', auth, async (req: any, res: any) => {
// machine-key action and Reconnect link on that field, not on connection.
const machineId = user?.botMetadata?.machineId;
const daemonBound = Boolean(machineId);
// Its owner stopped it, which is an answer, not a missing status. A
// daemon seat sharing the identity is still running, so it goes on.
const hostedRecord = readHostedConfig(i);
if (!daemonBound && runtimeType === 'hosted' && hostedRecord.deprovisionedAt && !hostedRecord.provisionedAt) {
return { ...payload, connection: { state: 'stopped', lastSeenAt: null } };
}
// The harness label moves to `adapter`, so the chat tag keeps naming it.
// The poller's report (TASK-704) outranks a stale runtimeType declaration:
// a seat declared codex that polls claude must not project codex here.
Expand Down
9 changes: 9 additions & 0 deletions backend/services/hostedEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,15 @@ export const nativeHostedConfigForInstall = (about?: string): Record<string, unk
...(about ? { about } : {}),
});

/**
* True once an owner has stopped a hosted install and not started it again.
* A row that was never provisioned has no stop to report.
*/
export const hostedIsStopped = (installation: any): boolean => {
const { deprovisionedAt, provisionedAt } = readHostedConfig(installation);
return isHostedInstallation(installation) && Boolean(deprovisionedAt) && !provisionedAt;
};

/**
* True for a provisioned hosted install whose turns run on the native
* runtime. A deprovisioned one routes nowhere, as a stopped Durable Object
Expand Down
15 changes: 15 additions & 0 deletions frontend/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1833,6 +1833,7 @@
"staleDays_one": "Not seen in {{count}} day",
"staleDays_other": "Not seen in {{count}} days",
"never": "Not connected yet",
"stopped": "Stopped",
"reconnect": "Reconnect",
"reconnectWaiting": "Waiting for your computer to reconnect this agent.",
"reconnectDone": "Connected.",
Expand Down Expand Up @@ -3179,6 +3180,20 @@
"heartbeatHostedOff": "Heartbeats aren't available yet for your agents that run on Commonly.",
"saveInterval": "Save interval",
"minutesShort": "{{minutes}} min",
"hostedRun": {
"running": "Running.",
"stopped": "Stopped. It won't answer until you start it.",
"starting": "Starting…",
"slow": "Still starting. If it stays this way, try Start again.",
"stop": "Stop",
"start": "Start",
"stopConfirm": "Stop it",
"keep": "Keep running",
"confirm": "Stop {{name}}? It won't answer until you start it again. Its memory and pods stay.",
"confirmClears": "Stop {{name}}? This clears its conversation history, and it won't answer until you start it again. Its pods stay.",
"stopError": "Couldn't stop {{name}}. Try again.",
"startError": "Couldn't start {{name}}. Try again."
},
"addToPod": {
"action": "Add to pod",
"choose": "Pod to add this agent to",
Expand Down
15 changes: 15 additions & 0 deletions frontend/src/i18n/locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -1890,6 +1890,7 @@
"staleHours": "已{{count}}小时未连接",
"staleDays_other": "已{{count}}天未连接",
"never": "尚未连接",
"stopped": "已停止",
"reconnect": "重新连接",
"reconnectWaiting": "正在等待电脑重新连接此智能体。",
"reconnectDone": "已连接。",
Expand Down Expand Up @@ -3180,6 +3181,20 @@
"heartbeatHostedOff": "你在 Commonly 上运行的智能体暂未开放心跳功能。",
"saveInterval": "保存间隔",
"minutesShort": "{{minutes}}分钟",
"hostedRun": {
"running": "运行中。",
"stopped": "已停止。重新启动前,它不会回复。",
"starting": "正在启动…",
"slow": "还在启动。如果一直这样,请再点一次启动。",
"stop": "停止",
"start": "启动",
"stopConfirm": "确认停止",
"keep": "继续运行",
"confirm": "要停止 {{name}} 吗?重新启动前,它不会回复。它的记忆和 Pod 都会保留。",
"confirmClears": "要停止 {{name}} 吗?这会清除它的对话记录,重新启动前它也不会回复。它所在的 Pod 会保留。",
"stopError": "无法停止 {{name}},请重试。",
"startError": "无法启动 {{name}},请重试。"
},
"addToPod": {
"action": "添加到 Pod",
"choose": "选择要添加到的 Pod",
Expand Down
Loading
Loading