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
5 changes: 5 additions & 0 deletions crates/goose/src/acp/server/new_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ struct InitialSessionConfig {
/// session row after it is created.
struct NewSessionMetaFields {
project_id: Option<String>,
scheduled_job_id: Option<String>,
/// Client-supplied title, recorded as user-set so goose's own name
/// generation leaves it alone. `None` when a recipe title took precedence.
client_title: Option<String>,
Expand Down Expand Up @@ -207,6 +208,9 @@ impl AcpConnection {
if let Some(project_id) = config.meta.project_id {
builder = builder.project_id(Some(project_id));
}
if let Some(scheduled_job_id) = config.meta.scheduled_job_id {
builder = builder.schedule_id(Some(scheduled_job_id));
}
if let Some(client_title) = config.meta.client_title {
builder = builder.user_provided_name(client_title);
}
Expand Down Expand Up @@ -283,6 +287,7 @@ fn new_session_meta_fields(
.filter(|title| !title.is_empty());
Ok(NewSessionMetaFields {
project_id: meta_string(meta, "projectId")?,
scheduled_job_id: meta_string(meta, "scheduledJobId")?,
// A recipe title is a server-side declaration, so it keeps the
// precedence it has today and a client title only replaces the
// "New Chat" fallback.
Expand Down
25 changes: 25 additions & 0 deletions crates/goose/tests/acp_server_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -903,6 +903,31 @@ fn test_new_session_uses_current_config_mode() {
run_test(async { run_new_session_uses_current_config_mode::<AcpServerConnection>().await });
}

#[test]
fn test_new_session_persists_scheduled_job_id() {
run_test(async {
let data_root = tempfile::tempdir().unwrap();
let conn = new_connection(data_root.path()).await;
let work_dir = tempfile::tempdir().unwrap();
let response = conn
.cx()
.send_request(
NewSessionRequest::new(work_dir.path()).meta(serde_json::Map::from_iter([
("client".to_string(), "goose-desktop".into()),
("scheduledJobId".to_string(), "daily-recipe".into()),
])),
)
.block_task()
.await
.unwrap();
let session = SessionManager::new(data_root.path().to_path_buf())
.get_session(&response.session_id.0, false)
.await
.unwrap();
assert_eq!(session.schedule_id.as_deref(), Some("daily-recipe"));
});
}

#[test]
fn test_new_session_response_precedes_available_commands() {
run_test(async {
Expand Down
1 change: 1 addition & 0 deletions ui/desktop/src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ const mockElectron = {
logInfo: vi.fn(),
on: vi.fn(),
off: vi.fn(),
onStartRecipe: vi.fn(() => () => {}),
reactReady: vi.fn(),
getAllowedExtensions: vi.fn().mockResolvedValue(null),
platform: 'darwin',
Expand Down
66 changes: 54 additions & 12 deletions ui/desktop/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import AnnouncementModal from './components/AnnouncementModal';
import TelemetryConsentPrompt from './components/TelemetryConsentPrompt';
import OnboardingGuard from './components/onboarding/OnboardingGuard';
import { createSession } from './sessions';
import { acpListSessions, acpDeleteSession } from './acp/sessions';
import { acpListSessions, acpDeleteSession, acpGetSessionListItem } from './acp/sessions';
import { acpChatSessionStore } from './acp/chatSessionStore';

import { ChatType } from './types/chat';
Expand Down Expand Up @@ -51,7 +51,7 @@ import { View, ViewOptions } from './utils/navigationUtils';

import { useNavigation } from './hooks/useNavigation';
import { errorMessage } from './utils/conversionUtils';
import { getInitialWorkingDir } from './utils/workingDir';
import { getEffectiveWorkingDir, getInitialWorkingDir } from './utils/workingDir';
import { usePageViewTracking } from './hooks/useAnalytics';
import { trackErrorWithContext } from './utils/analytics';
import { AppEvents } from './constants/events';
Expand Down Expand Up @@ -109,6 +109,7 @@ export const PairRouteWrapper = ({
const resumeSessionId = searchParams.get('resumeSessionId') ?? undefined;
const recipeDeeplinkFromConfig = window.appConfig?.get('recipeDeeplink') as string | undefined;
const recipeIdFromConfig = window.appConfig?.get('recipeId') as string | undefined;
const scheduledJobId = window.appConfig?.get('scheduledJobId') as string | undefined;
const initialMessage = routeState.initialMessage;
const noAutoSubmit = routeState.noAutoSubmit;

Expand All @@ -126,6 +127,7 @@ export const PairRouteWrapper = ({
const newSession = await createSession(getInitialWorkingDir(), {
recipeDeeplink: recipeDeeplinkFromConfig,
recipeId: recipeIdFromConfig,
scheduledJobId,
allExtensions: extensionsList,
});
const sessionInitialMessage = resolveSessionInitialMessage(newSession, initialMessage);
Expand Down Expand Up @@ -170,6 +172,7 @@ export const PairRouteWrapper = ({
initialMessage,
recipeDeeplinkFromConfig,
recipeIdFromConfig,
scheduledJobId,
resumeSessionId,
setSearchParams,
extensionsList,
Expand Down Expand Up @@ -423,16 +426,7 @@ export function AppInner() {
};
}, []);

const { addExtension } = useConfig();

useEffect(() => {
try {
window.electron.reactReady();
} catch (error) {
console.error('Error sending reactReady:', error);
setFatalError(`React ready notification failed: ${errorMessage(error, 'Unknown error')}`);
}
}, []);
const { addExtension, extensionsList } = useConfig();

useEffect(() => {
const handleSystemResume = () => reconnectAcpAfterSystemResume();
Expand Down Expand Up @@ -602,6 +596,54 @@ export function AppInner() {
};
}, [navigate]);

useEffect(() => {
return window.electron.onStartRecipe(async (payload) => {
try {
const sessionId =
location.pathname === '/pair'
? new URLSearchParams(location.search).get('resumeSessionId')
: null;
const workingDir = sessionId
? (acpChatSessionStore.getSnapshot(sessionId)?.session?.working_dir ??
(await acpGetSessionListItem(sessionId)).workingDir)
: await getEffectiveWorkingDir();
const newSession = await createSession(workingDir, {
...payload,
allExtensions: extensionsList,
});
window.dispatchEvent(
new CustomEvent(AppEvents.ADD_ACTIVE_SESSION, {
detail: {
sessionId: newSession.id,
initialMessage: resolveSessionInitialMessage(newSession),
},
})
);
Comment thread
Abhijay007 marked this conversation as resolved.
Resolved
navigate(`/pair?${new URLSearchParams({ resumeSessionId: newSession.id })}`);
} catch (error) {
if (isRecipeParamsCancelled(error)) {
navigate('/');
return;
}
if (isRecipeDeclined(error)) return;
if (isRecipeParameterScopesUnsupported(error)) {
toast.error(errorMessage(error));
return;
}
console.error('Failed to start recipe from deep link:', error);
}
});
}, [extensionsList, location.pathname, location.search, navigate]);

useEffect(() => {
try {
window.electron.reactReady();
} catch (error) {
console.error('Error sending reactReady:', error);
setFatalError(`React ready notification failed: ${errorMessage(error, 'Unknown error')}`);
}
}, []);

// Register platform event handlers for app lifecycle management
useEffect(() => {
return registerPlatformEventHandlers();
Expand Down
54 changes: 54 additions & 0 deletions ui/desktop/src/acp/__tests__/recipeParamRequests.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,4 +236,58 @@ describe('ACP recipe param requests', () => {
requests.cancelAcpRecipeParamRequest(laterRequest.id);
await laterResponse;
});

it('keeps concurrent recipe launches isolated when one scope finishes', async () => {
setRecipeParameters({ topic: 'first run' });
const firstScope = requests.beginConfiguredRecipeParameterScope()!;
const secondScope = requests.beginConfiguredRecipeParameterScope({ topic: 'second run' })!;
const firstResponse = requests.requestAcpRecipeParams(
recipeParamRequest('first', firstScope.id)
);
const secondResponse = requests.requestAcpRecipeParams(
recipeParamRequest('second', secondScope.id)
);
const [first, second] = requests.getAcpRecipeParamRequestsSnapshot();
expect(first.initialValues).toEqual({ topic: 'first run' });
expect(second.initialValues).toEqual({ topic: 'second run' });

firstScope.finish();
expect(
requests.getAcpRecipeParamRequestsSnapshot().map((request) => request.initialValues)
).toEqual([{}, { topic: 'second run' }]);
requests.cancelAcpRecipeParamRequest(first.id);
requests.resolveAcpRecipeParamRequest(second.id, { topic: 'second run' });
await expect(firstResponse).resolves.toEqual({ action: 'cancel' });
await expect(secondResponse).resolves.toEqual({
action: 'submit',
values: { topic: 'second run' },
});
secondScope.finish();
});

it('uses provided values directly instead of reading window.appConfig', async () => {
const get = setRecipeParameters({ topic: 'from config' });
const scope = requests.beginConfiguredRecipeParameterScope({ topic: 'from deeplink' })!;

expect(get).not.toHaveBeenCalled();

const response = requests.requestAcpRecipeParams(recipeParamRequest('session-1', scope.id));
const [pending] = requests.getAcpRecipeParamRequestsSnapshot();
expect(pending.initialValues).toEqual({ topic: 'from deeplink' });

requests.cancelAcpRecipeParamRequest(pending.id);
await response;
scope.finish();
});

it('never falls back to startup values for a parameterless warm link', () => {
const get = setRecipeParameters({ topic: 'startup' });
expect(requests.beginConfiguredRecipeParameterScope({})).toBeUndefined();
expect(get).not.toHaveBeenCalled();

const startupScope = requests.beginConfiguredRecipeParameterScope()!;
startupScope.finish();
expect(requests.beginConfiguredRecipeParameterScope({})).toBeUndefined();
expect(get).toHaveBeenCalledTimes(1);
});
});
2 changes: 2 additions & 0 deletions ui/desktop/src/acp/__tests__/sessions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ describe('ACP sessions', () => {
await acpNewSession('/tmp', undefined, {
recipeDeeplink: 'goose://recipe?url=example',
recipeParameterScopeId: 'scope-1',
scheduledJobId: 'daily-recipe',
});

expect(client.connection.agent.request).toHaveBeenCalledWith(methods.agent.session.new, {
Expand All @@ -181,6 +182,7 @@ describe('ACP sessions', () => {
client: 'goose-desktop',
recipeDeeplink: 'goose://recipe?url=example',
recipeParameterScopeId: 'scope-1',
scheduledJobId: 'daily-recipe',
},
});
});
Expand Down
Loading
Loading