Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Fix agent session navigation and provisioning failures

Wolf Mermelsteind8a8d6a3a504
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx
index 19593313c6..bdb78ca11d 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx
@@ -13,11 +13,7 @@ export const MagicChip: Component<MagicChipDecoratorProps> = (props) => {
<MagicChipView
agentSessionId={props.agentSessionId}
presentation={model.presentation()}
- onOpen={
- props.channelId
- ? () => insertSplit({ type: 'channel', id: props.channelId! })
- : undefined
- }
+ onOpen={() => insertSplit({ type: 'agent', id: props.agentSessionId })}
/>
);
};
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
index 11dca10790..1dca324290 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
@@ -7,8 +7,12 @@ const sessionFold = vi.hoisted(() => ({
acquireAgentSessionFold: vi.fn(),
subscribeAgentSessionLog: vi.fn(),
}));
+const serviceClient = vi.hoisted(() => ({ get: vi.fn() }));
vi.mock('@queries/agent-session/session-fold', () => sessionFold);
+vi.mock('@service-agent-harness/client', () => ({
+ agentHarnessServiceClient: serviceClient,
+}));
import { createMagicChipModel } from './create-magic-chip-model';
@@ -44,6 +48,10 @@ describe('createMagicChipModel', () => {
messages: [prompt, response],
release: vi.fn(),
});
+ serviceClient.get.mockResolvedValue({
+ isOk: () => true,
+ value: { status: { kind: 'disconnected' } },
+ });
});
it('settles after the attached turn completes despite stale acp_ready status', async () => {
@@ -63,4 +71,26 @@ describe('createMagicChipModel', () => {
dispose();
});
+
+ it('hydrates a disconnected status from the session', async () => {
+ sessionFold.acquireAgentSessionFold.mockResolvedValue({
+ messages: [],
+ release: vi.fn(),
+ });
+ let presentation!: ReturnType<typeof createMagicChipModel>['presentation'];
+ const dispose = createRoot((rootDispose) => {
+ presentation = createMagicChipModel(props).presentation;
+ return rootDispose;
+ });
+
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(presentation()).toEqual({
+ kind: 'working',
+ activity: { label: 'Session disconnected', busy: false },
+ });
+
+ dispose();
+ });
});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
index 7e4b9b2900..c248888701 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
@@ -1,16 +1,27 @@
-import type { MagicChipDecoratorProps } from '@macro-inc/lexical-core';
+import {
+ MAGIC_CHIP_STATUSES,
+ type MagicChipDecoratorProps,
+ type MagicChipStatus,
+} from '@macro-inc/lexical-core';
import {
acquireAgentSessionFold,
subscribeAgentSessionLog,
} from '@queries/agent-session/session-fold';
import type { FoldedMessage } from '@service-agent-fold/generated/types';
-import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';
+import { agentHarnessServiceClient } from '@service-agent-harness/client';
+import type {
+ AgentSessionLogEntryDto,
+ SessionStatusDto,
+} from '@service-agent-harness/generated/schemas';
import { type Accessor, createSignal, onCleanup } from 'solid-js';
import {
deriveMagicChipPresentation,
type MagicChipPresentation,
} from './presentation';
+const STATUS_POLL_INTERVAL_MS = 5_000;
+const MAX_STATUS_POLLS = 120;
+
function systemEvent(entry: AgentSessionLogEntryDto): string | undefined {
const content = entry.content;
return content.type === 'event' && typeof content.event === 'string'
@@ -18,14 +29,24 @@ function systemEvent(entry: AgentSessionLogEntryDto): string | undefined {
: undefined;
}
+function magicChipStatus(
+ status: SessionStatusDto
+): MagicChipStatus | undefined {
+ const value = status.kind === 'event' ? status.event : status.kind;
+ return MAGIC_CHIP_STATUSES.find((candidate) => candidate === value);
+}
+
/** Observe the session lifecycle and the chip's anchored folded turn. */
export function createMagicChipModel(props: MagicChipDecoratorProps): {
presentation: Accessor<MagicChipPresentation>;
} {
const [latestEvent, setLatestEvent] = createSignal<string>();
const [messages, setMessages] = createSignal<FoldedMessage[]>([]);
+ const [persistedStatus, setPersistedStatus] = createSignal(props.status);
let active = true;
let release: (() => void) | undefined;
+ let statusTimer: ReturnType<typeof setTimeout> | undefined;
+ let statusPolls = 0;
const unsubscribe = subscribeAgentSessionLog(
props.agentSessionId,
(event) => {
@@ -34,6 +55,24 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {
}
);
+ const refreshStatus = async () => {
+ statusPolls += 1;
+ const result = await agentHarnessServiceClient
+ .get(props.agentSessionId)
+ .catch(() => undefined);
+ if (!active) return;
+ const status = result?.isOk()
+ ? magicChipStatus(result.value.status)
+ : undefined;
+ if (status) setPersistedStatus(status);
+ const retry =
+ result === undefined || status === 'no_messages' || status === 'booting';
+ if (retry && statusPolls < MAX_STATUS_POLLS) {
+ statusTimer = setTimeout(refreshStatus, STATUS_POLL_INTERVAL_MS);
+ }
+ };
+ void refreshStatus();
+
void acquireAgentSessionFold({
agentSessionId: props.agentSessionId,
onChange: (changed) => {
@@ -66,6 +105,7 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {
onCleanup(() => {
active = false;
+ clearTimeout(statusTimer);
unsubscribe();
release?.();
});
@@ -76,7 +116,7 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {
(message) => message.turn === turn
);
return deriveMagicChipPresentation({
- persistedStatus: props.status,
+ persistedStatus: persistedStatus(),
latestEvent: latestEvent(),
prompt: messagesForTurn.find((message) => message.author.kind === 'user'),
response: messagesForTurn.find(
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index 0be0f43439..740dbc0117 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -362,13 +362,30 @@ where
})
.await?;
- let container = self
+ let container = match self
.containers
.spawn(SpawnContainer {
session_id,
repo_url,
})
- .await?;
+ .await
+ {
+ Ok(container) => container,
+ Err(error) => {
+ let _ = self
+ .sessions
+ .mark_disconnected(session_id)
+ .await
+ .inspect_err(|status_error| {
+ tracing::error!(
+ error = ?status_error,
+ %session_id,
+ "failed to mark an unprovisioned session disconnected"
+ );
+ });
+ return Err(error);
+ }
+ };
self.sessions
.attach_session(session_id, RuntimeAttachment::solo(container))
.await?;
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index 458b8d032d..79490584e2 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -239,6 +239,36 @@ async fn open_creates_announces_and_delivers_the_mention() {
);
}
+#[tokio::test]
+async fn a_provisioning_failure_marks_the_session_disconnected() {
+ let (service, repo, containers, _announcer, _runtimes) = harness();
+ let id = AgentSessionId::new();
+ containers.fail_next_spawn("capacity exhausted");
+
+ let error = service
+ .execute(id, HarnessCommand::Open(open_command()))
+ .await
+ .expect_err("open should fail");
+
+ assert!(matches!(error, HarnessError::Container(_)));
+ let log = repo
+ .list_by_session(id)
+ .await
+ .expect("session log can be read");
+ assert!(matches!(
+ &log[..],
+ [agent_session::domain::model::StoredAgentSessionLog {
+ entry: agent_session::domain::model::AgentSessionLog {
+ content: Message::ToServer(ToServerMessage::Event {
+ event: SystemEvent::Disconnected,
+ }),
+ ..
+ },
+ ..
+ }]
+ ));
+}
+
#[tokio::test]
async fn open_announces_while_the_container_is_still_booting() {
let (service, _repo, containers, announcer, _runtimes) = harness();
diff --git a/crates/agent_harness/src/testing/helpers/containers.rs b/crates/agent_harness/src/testing/helpers/containers.rs
index 96ac4a24dc..5a09f6eaec 100644
--- a/crates/agent_harness/src/testing/helpers/containers.rs
+++ b/crates/agent_harness/src/testing/helpers/containers.rs
@@ -195,6 +195,7 @@ impl TransportReceiver<ToServerMessage> for ContainerReceiver {
#[derive(Clone, Default)]
pub struct MockContainerManager {
containers: Arc<Mutex<HashMap<AgentSessionId, ContainerMock>>>,
+ spawn_error: Arc<Mutex<Option<String>>>,
resumes: Arc<AtomicUsize>,
teardowns: Arc<AtomicUsize>,
}
@@ -224,6 +225,14 @@ impl MockContainerManager {
self.lock().len()
}
+ /// Make the next sandbox spawn fail with `message`.
+ pub fn fail_next_spawn(&self, message: impl Into<String>) {
+ *self
+ .spawn_error
+ .lock()
+ .expect("spawn error lock should not be poisoned") = Some(message.into());
+ }
+
/// How many times an existing sandbox was requested.
#[must_use]
pub fn resumed(&self) -> usize {
@@ -247,6 +256,14 @@ impl ContainerManager for MockContainerManager {
type Transport = ContainerMock;
async fn spawn(&self, command: SpawnContainer) -> Result<ContainerMock, HarnessError> {
+ if let Some(message) = self
+ .spawn_error
+ .lock()
+ .expect("spawn error lock should not be poisoned")
+ .take()
+ {
+ return Err(HarnessError::Container(message));
+ }
let container = ContainerMock::default();
self.lock().insert(command.session_id, container.clone());
Ok(container)
diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rs
index a072264eab..298e9b7877 100644
--- a/crates/agent_session/src/domain/service.rs
+++ b/crates/agent_session/src/domain/service.rs
@@ -31,6 +31,7 @@ use agent_client_protocol::schema::v1::SessionId;
use agent_fold::domain::fold::FoldMachineImpl;
use agent_fold::domain::ports::{FoldMachine, FoldedMessageRepo};
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
+use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToServerMessage};
use dashmap::DashMap;
use dashmap::mapref::entry::Entry;
use macro_user_id::user_id::MacroUserIdStr;
@@ -79,6 +80,9 @@ pub trait AgentSessionService: Send + Sync + 'static {
/// is already in the state this asks for, so it succeeds.
fn close_session(&self, id: AgentSessionId) -> impl Future<Output = Result<()>> + Send;
+ /// Persist that a session disconnected before a live actor could report it.
+ fn mark_disconnected(&self, id: AgentSessionId) -> impl Future<Output = Result<()>> + Send;
+
/// Attach a new transport to an existing persisted session.
///
/// The attachment carries the connection's handshake gate as well as the
@@ -268,6 +272,18 @@ where
Ok(())
}
+ async fn mark_disconnected(&self, id: AgentSessionId) -> Result<()> {
+ let mut logs = LiveSessionLogWriter::new(self.repo.clone(), self.realtime.clone());
+ logs.append(AgentSessionLog {
+ agent_session_id: id,
+ user_id: None,
+ content: Message::ToServer(ToServerMessage::Event {
+ event: SystemEvent::Disconnected,
+ }),
+ })
+ .await
+ }
+
async fn attach_session<Connector>(
&self,
id: AgentSessionId,
diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rs
index 034462c314..025e103132 100644
--- a/crates/agent_session/src/domain/service/test.rs
+++ b/crates/agent_session/src/domain/service/test.rs
@@ -90,6 +90,41 @@ async fn appending_persists_the_event() {
assert_eq!(log.len(), 2);
}
+#[tokio::test]
+async fn marking_disconnected_persists_and_publishes_the_event() {
+ let repo = InMemoryAgentSessionRepo::new();
+ let session = test_session();
+ repo.insert_session(test_agent_session(session));
+ let realtime = RecordingRealtime::new();
+ let service = AgentSessionServiceImpl::new(
+ repo.clone(),
+ FoldedMessageService::new(repo.clone()),
+ realtime.clone(),
+ );
+
+ service
+ .mark_disconnected(session)
+ .await
+ .expect("disconnect is recorded");
+
+ let stored = AgentSessionLogRepo::list_by_session(&repo, session)
+ .await
+ .expect("stored log can be read");
+ assert!(matches!(
+ &stored[..],
+ [StoredAgentSessionLog {
+ entry: AgentSessionLog {
+ content: Message::ToServer(ToServerMessage::Event {
+ event: SystemEvent::Disconnected,
+ }),
+ ..
+ },
+ ..
+ }]
+ ));
+ assert_eq!(realtime.published().len(), 1);
+}
+
/// The point of the rework: a connection folds its session once, when it
/// starts, and every frame after that is folded into the state it kept.
///
diff --git a/infra/stacks/agent-harness-service/agent_harness_service.ts b/infra/stacks/agent-harness-service/agent_harness_service.ts
index e9267eadcf..d384c08fb8 100644
--- a/infra/stacks/agent-harness-service/agent_harness_service.ts
+++ b/infra/stacks/agent-harness-service/agent_harness_service.ts
@@ -245,7 +245,9 @@ export class AgentHarnessService extends pulumi.ComponentResource {
service: {
name: BASE_NAME,
image: image.image.imageUri,
- stopTimeout: 10,
+ // Daytona cleanup can make two 30-second stop attempts. Give the
+ // singleton time to release sandbox capacity before ECS kills it.
+ stopTimeout: 120,
cpu: 1024,
memory: 2048,
environment: [