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
113 changes: 96 additions & 17 deletions apps/web/src/components/ProjectView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1880,6 +1880,8 @@ export function ProjectView({
: projectRunWorkspaceContext
? 'workspace'
: 'pending';
const projectResourceAuthorityRef = useRef(projectResourceAuthority);
projectResourceAuthorityRef.current = projectResourceAuthority;
const projectRunWorkspaceContextRef = useRef(projectRunWorkspaceContext);
projectRunWorkspaceContextRef.current = projectRunWorkspaceContext;
// The AMR pre-run balance gate uses the project's resolved scope, or the one
Expand Down Expand Up @@ -3003,27 +3005,60 @@ export function ProjectView({
const reloadingCurrentConversation =
messagesConversationIdRef.current === activeConversationId
&& messagesAuthorityKeyRef.current === projectRunAuthorityKey;
const liveReloadMessageIds = new Set<string>();
if (
messagesConversationIdRef.current === activeConversationId
&& streamingConversationIdRef.current === activeConversationId
&& abortRef.current !== null
&& cancelRef.current !== null
&& projectResourceAuthorityRef.current !== 'denied'
) {
const currentMessages = messagesRef.current;
let assistantIndex = -1;
for (let index = currentMessages.length - 1; index >= 0; index -= 1) {
const message = currentMessages[index];
if (message?.role === 'assistant' && isActiveRunStatus(message.runStatus)) {
liveReloadMessageIds.add(message.id);
assistantIndex = index;
break;
}
}
for (let index = assistantIndex - 1; index >= 0; index -= 1) {
const message = currentMessages[index];
if (message?.role !== 'user') continue;
liveReloadMessageIds.add(message.id);
break;
}
}
const preservingLiveConversation = liveReloadMessageIds.size > 0;
// Reset the initialized flag so auto-send waits for this authoritative DB
// read to settle before checking messages.length. A same-conversation
// authority refresh keeps the prior transcript visible, but invalidates
// its initialized state until the refresh succeeds.
// authority refresh keeps the prior transcript visible. An authority-key
// handoff keeps only the live turn, so its pending read cannot detach the
// stream or later replace those rows with an empty snapshot.
setMessagesInitialized(false);
let cancelled = false;
const requestWorkspaceContext = projectRunWorkspaceContextRef.current;
setMessagesConversationId(null);
setFailedMessagesConversationId(null);
setStreaming(false);
streamingConversationIdRef.current = null;
setStreamingConversationId(null);
if (!preservingLiveConversation) {
setMessagesConversationId(null);
setStreaming(false);
streamingConversationIdRef.current = null;
setStreamingConversationId(null);
}
if (!reloadingCurrentConversation) {
setMessages([]);
setMessages((current) =>
preservingLiveConversation
? current.filter((message) => liveReloadMessageIds.has(message.id))
: [],
);
commitPreviewComments([]);
setAttachedComments([]);
setArtifact(null);
savedArtifactRef.current = null;
}
const commentsGeneration = previewCommentsGenerationRef.current;
if (!reloadingCurrentConversation) {
if (!reloadingCurrentConversation && !preservingLiveConversation) {
messagesConversationIdRef.current = null;
messagesAuthorityKeyRef.current = null;
}
Expand Down Expand Up @@ -3051,7 +3086,14 @@ export function ProjectView({
requestWorkspaceContext,
);
if (cancelled) return;
setMessages(normalizeConversationMessageOrder(list));
setMessages((current) =>
preservingLiveConversation
? mergeServerMessagesIntoConversation(
current.filter((message) => liveReloadMessageIds.has(message.id)),
list,
)
: normalizeConversationMessageOrder(list),
);
setMessagesInitialized(true);
setAttachedComments([]);
setArtifact(null);
Expand All @@ -3065,16 +3107,22 @@ export function ProjectView({
if (cancelled) return;
const message = err instanceof Error ? err.message : 'Could not load messages for this conversation.';
if (!reloadingCurrentConversation) {
setMessages([]);
setMessages((current) =>
preservingLiveConversation
? current.filter((item) => liveReloadMessageIds.has(item.id))
: [],
);
commitPreviewComments([]);
setAttachedComments([]);
setArtifact(null);
savedArtifactRef.current = null;
}
setError(message);
messagesConversationIdRef.current = null;
messagesAuthorityKeyRef.current = null;
setMessagesConversationId(null);
if (!preservingLiveConversation) {
messagesConversationIdRef.current = null;
messagesAuthorityKeyRef.current = null;
setMessagesConversationId(null);
}
setFailedMessagesConversationId(activeConversationId);
}
})();
Expand Down Expand Up @@ -7043,14 +7091,45 @@ export function ProjectView({
let streamedText = '';

const updateAssistant = (updater: (prev: ChatMessage) => ChatMessage) => {
setMessages((curr) =>
curr.map((m) => {
setMessages((curr) => {
let found = false;
const next = curr.map((m) => {
if (m.id !== assistantId) return m;
found = true;
const updated = updater(m);
latestAssistantMsg = updated;
return updated;
}),
);
});
if (found) return next;

// A workspace-authority refresh can reload the same conversation
// while POST /runs is retrying. That authoritative read may still
// be empty and replace the Home handoff's client-owned user and
// assistant placeholders. The stream remains attached, however, so
// dropping later deltas here leaves a successful daemon run blank
// until a tab switch or reload reads the persisted transcript.
//
// Restore only the two rows owned by the live controller for the
// project and conversation still on screen. A revoked authority is
// never allowed to resurrect them, and settled historical messages
// keep the existing clear-on-authority-change behavior.
if (
abortRef.current !== controller
|| projectIdRef.current !== project.id
|| activeConversationIdRef.current !== runConversationId
|| projectResourceAuthorityRef.current === 'denied'
) {
return curr;
}
const updated = updater(latestAssistantMsg);
latestAssistantMsg = updated;
const userAlreadyPresent = curr.some((message) => message.id === userMsg.id);
return [
...curr,
...(userAlreadyPresent ? [] : [userMsg]),
updated,
];
});
};
let persistTimer: ReturnType<typeof setTimeout> | null = null;
const persistAssistantSoon = () => {
Expand Down
201 changes: 201 additions & 0 deletions apps/web/tests/components/ProjectView.run-workspace-identity.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -646,6 +646,207 @@ describe('a Home auto-send identifies its caller before the project scope resolv
expect(mockedStreamViaDaemon).not.toHaveBeenCalled();
});

it('keeps a cold Home run attached when an empty authority refresh settles after stream events', async () => {
const activeStream = deferred<void>();
let runOptions: Parameters<typeof streamViaDaemon>[0] | undefined;
mockedStreamViaDaemon.mockImplementation((options) => {
runOptions = options;
return activeStream.promise;
});

const view = renderProjectView();

await waitFor(() => expect(runOptions).toBeDefined());
await waitFor(() => {
expect(chatPaneSpy.mock.calls.at(-1)?.[0].messages).toEqual([
expect.objectContaining({ role: 'user', content: SEED_PROMPT }),
expect.objectContaining({ role: 'assistant', runStatus: 'running' }),
]);
});

const authorityReload = deferred<ChatMessage[]>();
mockedListMessages.mockReturnValueOnce(authorityReload.promise);
workspaceScopeMocks.projectScope = {
loading: false,
scope: {
kind: 'team',
projectId: PROJECT_ID,
workspaceId: TEAM_WORKSPACE,
visibility: 'team',
context: {
...CALLER_CONTEXT,
role: 'admin',
permissions: buildWorkspacePermissions({
role: 'admin',
lifecycleState: 'active',
}),
} as WorkspaceCollabContext & { workspaceType: 'team' },
},
};
await act(async () => {
view.rerender(projectViewElement());
});

await waitFor(() => expect(mockedListMessages).toHaveBeenCalledTimes(2));
const expectedOutput = 'The first packaged run is still live.';
await act(async () => {
runOptions?.onRunCreated?.('run-first-home');
runOptions?.onRunStatus?.('running');
runOptions?.handlers.onAgentEvent({ kind: 'text', text: expectedOutput });
runOptions?.handlers.onAgentEvent({
kind: 'tool_use',
id: 'write-index',
name: 'Write',
input: { file_path: 'index.html', content: '<main>ready</main>' },
});
});

await waitFor(() => {
expect(chatPaneSpy.mock.calls.at(-1)?.[0].messages).toEqual([
expect.objectContaining({ role: 'user', content: SEED_PROMPT }),
expect.objectContaining({
role: 'assistant',
runId: 'run-first-home',
events: expect.arrayContaining([
expect.objectContaining({ kind: 'text', text: expectedOutput }),
]),
}),
]);
});

await act(async () => {
authorityReload.resolve([]);
await authorityReload.promise;
});

expect(chatPaneSpy.mock.calls.at(-1)?.[0].messages).toEqual([
expect.objectContaining({ role: 'user', content: SEED_PROMPT }),
expect.objectContaining({
role: 'assistant',
runId: 'run-first-home',
events: expect.arrayContaining([
expect.objectContaining({ kind: 'text', text: expectedOutput }),
]),
}),
]);

activeStream.resolve();
});

it('keeps a terminal cold Home run attached when the empty refresh outlives its controller', async () => {
const activeStream = deferred<void>();
let runOptions: Parameters<typeof streamViaDaemon>[0] | undefined;
mockedStreamViaDaemon.mockImplementation((options) => {
runOptions = options;
return activeStream.promise;
});

const view = renderProjectView();
await waitFor(() => expect(runOptions).toBeDefined());

const authorityReload = deferred<ChatMessage[]>();
mockedListMessages.mockReturnValueOnce(authorityReload.promise);
workspaceScopeMocks.projectScope = {
loading: false,
scope: {
kind: 'team',
projectId: PROJECT_ID,
workspaceId: TEAM_WORKSPACE,
visibility: 'team',
context: {
...CALLER_CONTEXT,
role: 'admin',
permissions: buildWorkspacePermissions({
role: 'admin',
lifecycleState: 'active',
}),
} as WorkspaceCollabContext & { workspaceType: 'team' },
},
};
await act(async () => {
view.rerender(projectViewElement());
});
await waitFor(() => expect(mockedListMessages).toHaveBeenCalledTimes(2));

const expectedOutput = 'The terminal first run stays visible.';
await act(async () => {
runOptions?.onRunCreated?.('run-terminal-home');
runOptions?.onRunStatus?.('running');
runOptions?.handlers.onAgentEvent({ kind: 'text', text: expectedOutput });
runOptions?.handlers.onAgentEvent({
kind: 'tool_use',
id: 'write-terminal-index',
name: 'Write',
input: { file_path: 'index.html', content: '<main>complete</main>' },
});
runOptions?.onRunStatus?.('succeeded');
});

await act(async () => {
authorityReload.resolve([]);
await authorityReload.promise;
runOptions?.handlers.onDone('');
});

expect(chatPaneSpy.mock.calls.at(-1)?.[0].messages).toEqual([
expect.objectContaining({ role: 'user', content: SEED_PROMPT }),
expect.objectContaining({
role: 'assistant',
runId: 'run-terminal-home',
endedAt: expect.any(Number),
events: expect.arrayContaining([
expect.objectContaining({ kind: 'text', text: expectedOutput }),
]),
}),
]);

activeStream.resolve();
});

it('does not restore a cold Home run after project authority is revoked', async () => {
const activeStream = deferred<void>();
let runOptions: Parameters<typeof streamViaDaemon>[0] | undefined;
mockedStreamViaDaemon.mockImplementation((options) => {
runOptions = options;
return activeStream.promise;
});

const view = renderProjectView();
await waitFor(() => expect(runOptions).toBeDefined());

workspaceScopeMocks.ambientContext = null;
workspaceScopeMocks.projectScope = {
loading: false,
scope: null,
failure: 'forbidden',
};
await act(async () => {
view.rerender(projectViewElement());
});

await waitFor(() => expect(mockedListMessages).toHaveBeenCalledTimes(2));
await waitFor(() => {
expect(chatPaneSpy.mock.calls.at(-1)?.[0].messages).toEqual([]);
});

await act(async () => {
runOptions?.onRunCreated?.('run-revoked-home');
runOptions?.handlers.onAgentEvent({
kind: 'text',
text: 'This output belongs to the revoked authority.',
});
runOptions?.handlers.onAgentEvent({
kind: 'tool_use',
id: 'revoked-write',
name: 'Write',
input: { file_path: 'index.html', content: '<main>private</main>' },
});
});

expect(chatPaneSpy.mock.calls.at(-1)?.[0].messages).toEqual([]);
activeStream.resolve();
});

it('reuses one Home handoff identity across ProjectView remounts', async () => {
const firstView = renderProjectView();
await waitFor(() => expect(mockedStreamViaDaemon).toHaveBeenCalledTimes(1));
Expand Down
Loading
Loading