Skip to content

The agent that grows with you

Guided first launch: the first build connects the picked apps before it starts (NS-859) (#108317)

Siddharth Balyan474a7f8b2ae0
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
index 958364e303d..2d04ce8720b 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
@@ -222,6 +222,7 @@ export function useComposerQueue({
onSubmit(entry.text, {
attachments: entry.attachments,
...(entry.displayText ? { displayText: entry.displayText } : {}),
+ ...(entry.displayKind ? { displayKind: entry.displayKind } : {}),
fromQueue: true,
sessionId: drainRuntimeSessionId,
storedSessionId: drainQueueSessionKey
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
index b05a47a5818..eefc217e65e 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
@@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { PaneVisibleContext } from '@/components/pane-shell/pane-visibility'
import { $clarifyRequests } from '@/store/clarify'
import type { ComposerAttachment } from '@/store/composer'
+import { clearQueuedPrompts, getQueuedPrompts } from '@/store/composer-queue'
import { $gateway } from '@/store/gateway'
import {
clearAllPrompts,
@@ -54,7 +55,10 @@ function renderSubmitHook({
const editorRef = { current: editor }
const onCancel = vi.fn()
const onSteer = vi.fn(async () => true)
+ const onSteerHidden = vi.fn(async () => true)
const onSubmit = vi.fn(async () => true)
+ const loadIntoComposer = vi.fn()
+ const stashAt = vi.fn()
const queueCurrentDraft = vi.fn(() => true)
let updatePaneVisible: Dispatch<SetStateAction<boolean>> | undefined
@@ -106,16 +110,17 @@ function renderSubmitHook({
exitQueuedEdit: vi.fn(() => false),
focusInput: vi.fn(),
inputDisabled,
- loadIntoComposer: vi.fn(),
+ loadIntoComposer,
onCancel,
onSteer,
+ onSteerHidden,
onSubmit,
queueCurrentDraft,
queueEdit: null,
queuedPrompts: [],
sessionId: 'runtime-session',
setComposerText: vi.fn(),
- stashAt: vi.fn()
+ stashAt
}),
{ wrapper: Wrapper }
)
@@ -125,7 +130,10 @@ function renderSubmitHook({
hook,
onCancel,
onSteer,
+ onSteerHidden,
onSubmit,
+ loadIntoComposer,
+ stashAt,
queueCurrentDraft,
composerSurfaceId: resolvedSurfaceId,
setPaneVisible(nextVisible: boolean) {
@@ -141,9 +149,69 @@ function renderSubmitHook({
describe('useComposerSubmit external request routing', () => {
afterEach(() => {
cleanup()
+ clearQueuedPrompts('stored-session')
vi.restoreAllMocks()
})
+ it.each([true, false])('steers a busy external visible submit and queues only on rejection (%s)', async accepted => {
+ const { onSteer, onSubmit, clearDraft } = renderSubmitHook({ busy: true, text: 'unsent draft' })
+ onSteer.mockResolvedValue(accepted)
+
+ await act(async () => {
+ expect(requestComposerSubmit('Start without connections.', { target: 'main' })).toBe(true)
+ })
+
+ expect(onSteer).toHaveBeenCalledExactlyOnceWith('Start without connections.')
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(clearDraft).not.toHaveBeenCalled()
+ expect(getQueuedPrompts('stored-session').map(({ text, attachments }) => ({ text, attachments }))).toEqual(
+ accepted ? [] : [{ text: 'Start without connections.', attachments: [] }]
+ )
+
+ await act(async () => {
+ requestComposerSubmit('/status', { target: 'main' })
+ })
+ expect(getQueuedPrompts('stored-session').at(-1)?.text).toBe('/status')
+ expect(onSteer).toHaveBeenCalledTimes(1)
+ expect(onSubmit).not.toHaveBeenCalled()
+ })
+
+ it.each([true, false])('delivers a busy hidden request as a steer with no user turn and queues it hidden on refusal (%s)', async accepted => {
+ const { onSteer, onSteerHidden, onSubmit, loadIntoComposer, stashAt } = renderSubmitHook({ busy: true })
+ onSteerHidden.mockResolvedValue(accepted)
+
+ await act(async () => {
+ requestComposerSubmit('[setup] links opened', { target: 'main', displayKind: 'hidden' })
+ })
+
+ expect(onSteerHidden).toHaveBeenCalledExactlyOnceWith('[setup] links opened')
+ expect(onSteer).not.toHaveBeenCalled()
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(getQueuedPrompts('stored-session').map(({ text, displayKind }) => ({ text, displayKind }))).toEqual(
+ accepted ? [] : [{ text: '[setup] links opened', displayKind: 'hidden' }]
+ )
+ expect(loadIntoComposer).not.toHaveBeenCalled()
+ expect(stashAt).not.toHaveBeenCalled()
+ })
+
+ it('drops an idle hidden request the gateway rejects instead of restoring it into the draft', async () => {
+ const { onSteer, onSubmit, loadIntoComposer, stashAt } = renderSubmitHook({ busy: false })
+ onSubmit.mockResolvedValue(false)
+
+ await act(async () => {
+ requestComposerSubmit('[setup] links opened', { target: 'main', displayKind: 'hidden' })
+ })
+
+ expect(onSubmit).toHaveBeenCalledExactlyOnceWith('[setup] links opened', {
+ composerScope: 'stored-session',
+ displayKind: 'hidden'
+ })
+ expect(onSteer).not.toHaveBeenCalled()
+ expect(getQueuedPrompts('stored-session')).toEqual([])
+ expect(loadIntoComposer).not.toHaveBeenCalled()
+ expect(stashAt).not.toHaveBeenCalled()
+ })
+
it('does not fan out a main ship across keep-alives or other projects', async () => {
const visibleMain = renderSubmitHook({ sessionKey: 'session-a' })
const hiddenMain = renderSubmitHook({ sessionKey: 'session-b', visible: false })
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
index e33f7388bba..d1ee2c15045 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
@@ -34,6 +34,7 @@ interface UseComposerSubmitArgs {
loadIntoComposer: (text: string, attachments: ComposerAttachment[]) => void
onCancel: ChatBarProps['onCancel']
onSteer: ChatBarProps['onSteer']
+ onSteerHidden: ChatBarProps['onSteerHidden']
onSubmit: ChatBarProps['onSubmit']
queueCurrentDraft: () => boolean
queueEdit: QueueEditState | null
@@ -69,6 +70,7 @@ export function useComposerSubmit({
loadIntoComposer,
onCancel,
onSteer,
+ onSteerHidden,
onSubmit,
queueCurrentDraft,
queueEdit,
@@ -96,13 +98,17 @@ export function useComposerSubmit({
stashAt(submittedScope, text, submittedAttachments)
}
+ // A hidden submit is machine text (a setup note, never something the user
+ // typed), so a rejection drops it instead of loading it into the draft.
+ const rejected = displayKind ? () => {} : restore
+
void Promise.resolve(
attachments
? onSubmit(text, { attachments, composerScope: submittedScope, ...(displayKind ? { displayKind } : {}) })
: onSubmit(text, { composerScope: submittedScope, ...(displayKind ? { displayKind } : {}) })
)
- .then(accepted => void (accepted === false ? restore() : clearSessionDraft(submittedScope)))
- .catch(restore)
+ .then(accepted => void (accepted === false ? rejected() : clearSessionDraft(submittedScope)))
+ .catch(rejected)
}
// External "submit this prompt" requests (e.g. the review pane's agent-ship
@@ -113,26 +119,11 @@ export function useComposerSubmit({
// Busy: a request from a card the user just clicked must not be dropped
// because the agent is mid-sentence — that gap is exactly when they click.
// Steer the live turn (the same stop-and-correct a typed message gets), and
- // if the turn has already ended, queue it so it runs next.
- const dispatchSubmitRef = useRef(dispatchSubmit)
- dispatchSubmitRef.current = dispatchSubmit
- const steerOrQueueRef = useRef((_text: string) => {})
-
- steerOrQueueRef.current = (text: string) => {
- const queue = () => enqueueQueuedPrompt(activeQueueSessionKeyRef.current, { text, attachments: [] })
-
- if (!onSteer) {
- queue()
-
- return
- }
-
- void Promise.resolve(onSteer(text)).then(accepted => {
- if (!accepted) {
- queue()
- }
- })
- }
+ // if the turn has already ended, or a steer is not possible, queue it so it
+ // runs next. This holds for hidden setup notes and for visible messages a
+ // button sends on the user's behalf alike.
+ const externalSubmitRef = useRef({ busy, compacting, dispatchSubmit, onSteer, onSteerHidden })
+ externalSubmitRef.current = { busy, compacting, dispatchSubmit, onSteer, onSteerHidden }
useLayoutEffect(
() =>
@@ -144,14 +135,56 @@ export function useComposerSubmit({
paneVisible &&
!inputDisabled
) {
- if (busy && displayKind === 'hidden') {
- steerOrQueueRef.current(text)
+ const current = externalSubmitRef.current
+
+ if (!current.busy) {
+ current.dispatchSubmit(text, undefined, displayKind)
+
+ return
+ }
+
+ const queueKey = activeQueueSessionKeyRef.current
+ // External requests contain only text; the unsent draft and its attachments stay in the composer.
+ const enqueue = () => void enqueueQueuedPrompt(queueKey, { text, attachments: [], ...(displayKind ? { displayKind } : {}) })
+
+ // A hidden note never becomes a user turn: it rides session.steer into
+ // the model's next tool result, and keeps its kind if it has to queue.
+ if (displayKind) {
+ if (current.onSteerHidden) {
+ void Promise.resolve(current.onSteerHidden(text))
+ .then(accepted => {
+ if (!accepted) {
+ enqueue()
+ }
+ })
+ .catch(enqueue)
+ } else {
+ enqueue()
+ }
+
+ return
+ }
+
+ if (
+ current.onSteer &&
+ !current.compacting &&
+ !hasBlockingPromptRequest(sessionId) &&
+ text.trim() &&
+ !SLASH_COMMAND_RE.test(text.trim())
+ ) {
+ void Promise.resolve(current.onSteer(text))
+ .then(accepted => {
+ if (!accepted) {
+ enqueue()
+ }
+ })
+ .catch(enqueue)
} else {
- dispatchSubmitRef.current(text, undefined, displayKind)
+ enqueue()
}
}
}),
- [busy, inputDisabled, paneVisible, scope.target, surfaceId]
+ [activeQueueSessionKeyRef, inputDisabled, paneVisible, scope.target, sessionId, surfaceId]
)
const submitDraft = () => {
diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsx
index fb3bf03da01..ac0097a7352 100644
--- a/apps/desktop/src/app/chat/composer/index.tsx
+++ b/apps/desktop/src/app/chat/composer/index.tsx
@@ -7,6 +7,7 @@ import { useHudComposerDrag } from '@/app/hud/composer-drag'
import { composerFill, composerFloatingStrip, composerSurfaceGlass } from '@/components/chat/composer-dock'
import { $chatOnboardingSolo, $chatOnboardingThreadIds } from '@/components/onboarding-chat/assembly'
import { OnboardingSkip } from '@/components/onboarding-chat/skip'
+import { OnboardingStart } from '@/components/onboarding-chat/start'
import { Button } from '@/components/ui/button'
import { Slot as ContribSlot } from '@/contrib/react/slot'
import { useI18n } from '@/i18n'
@@ -110,6 +111,7 @@ export function ChatBar({
onPickImages,
onRemoveAttachment,
onSteer,
+ onSteerHidden,
onSubmit: onSubmitProp,
onTranscribeAudio
}: ChatBarProps) {
@@ -389,6 +391,7 @@ export function ChatBar({
// empty composer) — an explicit halt, so it parks the queue.
onCancel: haltRun,
onSteer,
+ onSteerHidden,
onSubmit,
queueCurrentDraft,
queueEdit,
@@ -1200,6 +1203,7 @@ export function ChatBar({
<ActionBadges sessionId={statusSessionId} />
<SuggestionPills sessionId={statusSessionId} />
<OnboardingSkip />
+ <OnboardingStart />
</div>
{/* Session-scoped status stack (todos, subagents, background tasks,
queue). An in-flow dock child: the dock is bottom-anchored, so it
diff --git a/apps/desktop/src/app/chat/composer/queue-panel.tsx b/apps/desktop/src/app/chat/composer/queue-panel.tsx
index 01290bfe1d8..4fde7cc14e3 100644
--- a/apps/desktop/src/app/chat/composer/queue-panel.tsx
+++ b/apps/desktop/src/app/chat/composer/queue-panel.tsx
@@ -25,7 +25,9 @@ interface QueuePanelProps {
}
const entryPreview = (entry: QueuedPromptEntry, c: Translations['composer']) =>
- (entry.displayText ?? entry.text).trim() || (entry.attachments.length > 0 ? c.attachmentOnly : c.emptyTurn)
+ entry.displayKind === 'hidden'
+ ? c.hiddenQueued
+ : (entry.displayText ?? entry.text).trim() || (entry.attachments.length > 0 ? c.attachmentOnly : c.emptyTurn)
export function QueuePanel({
busy,
diff --git a/apps/desktop/src/app/chat/composer/types.ts b/apps/desktop/src/app/chat/composer/types.ts
index da6a463cd38..56516b558b6 100644
--- a/apps/desktop/src/app/chat/composer/types.ts
+++ b/apps/desktop/src/app/chat/composer/types.ts
@@ -55,6 +55,8 @@ export interface ChatBarProps {
onPickImages?: () => void
onRemoveAttachment?: (id: string) => void
onSteer?: (text: string) => Promise<boolean> | boolean
+ /** Delivers a hidden note to the model mid-turn with no user turn (gateway session.steer). */
+ onSteerHidden?: (text: string) => Promise<boolean> | boolean
onSubmit: (value: string, options?: SubmitTextOptions) => Promise<boolean> | boolean
onTranscribeAudio?: (audio: Blob) => Promise<string>
}
diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsx
index 1b95bc769a2..49dd37ac0b9 100644
--- a/apps/desktop/src/app/chat/index.tsx
+++ b/apps/desktop/src/app/chat/index.tsx
@@ -102,6 +102,7 @@ interface ChatViewProps extends Omit<React.ComponentProps<'div'>, 'onSubmit'> {
onPickImages: () => void
onRemoveAttachment: (id: string) => void
onSteer: (text: string) => Promise<boolean> | boolean
+ onSteerHidden?: (text: string) => Promise<boolean> | boolean
onSubmit: (text: string, options?: SubmitTextOptions) => Promise<boolean> | boolean
onThreadMessagesChange: (messages: readonly ThreadMessage[]) => void
onEdit: (message: AppendMessage) => Promise<void>
@@ -396,6 +397,7 @@ const ChatViewContent = memo(function ChatViewContent({
onPickImages,
onRemoveAttachment,
onSteer,
+ onSteerHidden,
onSubmit,
onThreadMessagesChange,
onEdit,
@@ -763,6 +765,7 @@ const ChatViewContent = memo(function ChatViewContent({
onPickImages={onPickImages}
onRemoveAttachment={onRemoveAttachment}
onSteer={onSteer}
+ onSteerHidden={onSteerHidden}
onSubmit={onSubmit}
onTranscribeAudio={onTranscribeAudio}
queueSessionKey={queueSessionKey}
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.ts
index 84648ed8159..5759cf484e5 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.ts
@@ -363,6 +363,37 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
}
}, [bindRecoveredRuntime, copy.stopFailed, requestSessionGateway, update])
+ // A hidden note mid-turn rides session.steer into the model's next tool
+ // result: no optimistic bubble, no user turn. The main composer has the same
+ // primitive in use-prompt-actions.
+ const injectHiddenPrompt = useCallback(
+ async (rawText: string): Promise<boolean> => {
+ const text = rawText.trim()
+ const sessionId = runtimeIdRef.current
+
+ if (!text || !sessionId) {
+ return false
+ }
+
+ try {
+ const { result } = await withSessionNotFoundResume(
+ sessionId,
+ storedIdRef.current,
+ liveId => requestSessionGateway<{ status?: string }>('session.steer', { session_id: liveId, text }),
+ {
+ requestGateway: requestSessionGateway,
+ onRecovered: bindRecoveredRuntime
+ }
+ )
+
+ return result?.status === 'queued'
+ } catch {
+ return false
+ }
+ },
+ [bindRecoveredRuntime, requestSessionGateway]
+ )
+
const steerPrompt = useCallback(
async (rawText: string): Promise<boolean> => {
const text = rawText.trim()
@@ -652,6 +683,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
dismissError,
editMessage,
handleThreadMessagesChange,
+ injectHiddenPrompt,
reloadFromMessage,
restoreToMessage,
steerPrompt,
@@ -662,6 +694,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
dismissError,
editMessage,
handleThreadMessagesChange,
+ injectHiddenPrompt,
reloadFromMessage,
restoreToMessage,
steerPrompt,
diff --git a/apps/desktop/src/app/chat/session-tile.tsx b/apps/desktop/src/app/chat/session-tile.tsx
index 899c0266763..90bd7c70b27 100644
--- a/apps/desktop/src/app/chat/session-tile.tsx
+++ b/apps/desktop/src/app/chat/session-tile.tsx
@@ -321,6 +321,7 @@ function TileChat({
onRestoreToMessage={actions.restoreToMessage}
onRetryResume={onRetryResume}
onSteer={actions.steerPrompt}
+ onSteerHidden={actions.injectHiddenPrompt}
onSubmit={actions.submitText}
onThreadMessagesChange={actions.handleThreadMessagesChange}
onToggleSelectedPin={noop}
diff --git a/apps/desktop/src/app/contrib/handoff-leg.ts b/apps/desktop/src/app/contrib/handoff-leg.ts
index 278bf141672..c6e4d058125 100644
--- a/apps/desktop/src/app/contrib/handoff-leg.ts
+++ b/apps/desktop/src/app/contrib/handoff-leg.ts
@@ -6,6 +6,7 @@ import type { ClientSessionState } from '@/app/types'
import type { HandoffPlan } from '@/components/onboarding-chat/setup-profile'
import type { SessionMessage } from '@/types/hermes'
+import { markFirstBuildSession } from './handoff-receipt'
import type { AmbientGatewayRequest } from './session-rpc-dispatcher'
export const BUILD_PROFILE = 'default'
@@ -76,6 +77,7 @@ export async function startHandoff(deps: HandoffDeps, task: HandoffTask, recover
const identity = await deps.create()
receipt = { ...task, ...identity, status: 'created' }
deps.save(receipt)
+ markFirstBuildSession(receipt.storedId)
} else {
const snapshot = await deps.request<HandoffSnapshot>(receipt.owner, 'session.resume', {
session_id: receipt.storedId,
diff --git a/apps/desktop/src/app/contrib/handoff-receipt.ts b/apps/desktop/src/app/contrib/handoff-receipt.ts
index 876e7ae0419..92fbdeecc95 100644
--- a/apps/desktop/src/app/contrib/handoff-receipt.ts
+++ b/apps/desktop/src/app/contrib/handoff-receipt.ts
@@ -6,6 +6,22 @@ import type { HandoffReceipt } from './handoff-leg'
// Nothing is submitted until the next save verifies durable persistence.
const unsavedReceipts = new Map<string, HandoffReceipt>()
+export function markFirstBuildSession(storedId: string): void {
+ writeKey('hermes.onboarding.first-build.v1', storedId)
+}
+
+export function endFirstBuildConnect(storedId: string): void {
+ writeKey('hermes.onboarding.first-build.done.v1', storedId)
+}
+
+export function isFirstBuildSession(storedId: string | null | undefined): boolean {
+ return (
+ !!storedId &&
+ readKey('hermes.onboarding.first-build.v1') === storedId &&
+ readKey('hermes.onboarding.first-build.done.v1') !== storedId
+ )
+}
+
/** A navigation/submit receipt, never a copy of either profile's memory. */
export function handoffReceiptKey(connection: null | string, guideStoredId: string): string {
return `hermes.onboarding.handoff.v1.connection.${encodeURIComponent(connection ?? 'ambient')}.profile.default.guide.${encodeURIComponent(guideStoredId)}`
diff --git a/apps/desktop/src/app/contrib/onboarding-handoff.ts b/apps/desktop/src/app/contrib/onboarding-handoff.ts
index d78f9e1fda1..3c153d02769 100644
--- a/apps/desktop/src/app/contrib/onboarding-handoff.ts
+++ b/apps/desktop/src/app/contrib/onboarding-handoff.ts
@@ -18,10 +18,11 @@ import {
retrySetupHandoff,
SETUP_PROFILE
} from '@/components/onboarding-chat/setup-profile'
-import { declinedLookAround, showProfileSignpost } from '@/components/onboarding-chat/signpost'
+import { showHandoffTour } from '@/components/onboarding-chat/signpost'
import { findGroupOfPane } from '@/components/pane-shell/tree/model'
import { $layoutTree, activateTreePane } from '@/components/pane-shell/tree/store'
import { toChatMessages } from '@/lib/chat-messages'
+import { connectorTitle } from '@/lib/connector-tools'
import { isOnboardingEnabled } from '@/lib/onboarding-enabled'
import { requestGatewayForAgent } from '@/store/gateway'
import { dismissNotification, notify } from '@/store/notifications'
@@ -30,7 +31,6 @@ import { beginOnboardingHandoff, completeOnboardingFlow } from '@/store/onboardi
import { $activeGatewayProfile, $newChatProfile, $newChatRoute, ensureGatewayAgent } from '@/store/profile'
import {
$activeSessionId,
- $messages,
$selectedStoredSessionId,
forgetSessionOwnerHintsForSession,
setActiveSessionId,
@@ -132,7 +132,6 @@ export function useOnboardingHandoff({
const setupSession = setupHandoff.guide ?? $setupSession.get()
const connectionId = setupSession?.connectionId ?? null
- const signpost = !declinedLookAround($messages.get())
const previousNewChatProfile = $newChatProfile.get()
const previousNewChatRoute = $newChatRoute.get()
let receipt: HandoffReceipt | null = null
@@ -160,10 +159,12 @@ export function useOnboardingHandoff({
saveHandoffReceipt(receiptKey, value)
},
personalize: async () => {
+ const answers = $onboardingAnswers.get()
+
const result = await request<{ saved?: boolean; profile?: string; target?: string }>(
owner,
'profiles.remember_onboarding',
- { answers: $onboardingAnswers.get() }
+ { answers: { ...answers, connectors: answers.connectors.map(connectorTitle) } }
)
if (!result.saved || result.profile !== BUILD_PROFILE || result.target !== 'user') {
@@ -282,8 +283,8 @@ export function useOnboardingHandoff({
PROMPT_SUBMIT_REQUEST_TIMEOUT_MS
).catch(error => console.warn('[handoff] guide note was not delivered', error))
- if (signpost && $selectedStoredSessionId.get() === receipt.storedId) {
- void showProfileSignpost()
+ if ($selectedStoredSessionId.get() === receipt.storedId) {
+ void showHandoffTour()
}
} catch (error) {
console.error('[handoff] first build needs recovery', error)
diff --git a/apps/desktop/src/app/contrib/types.ts b/apps/desktop/src/app/contrib/types.ts
index 44b8df9a4b3..77e853ed6e9 100644
--- a/apps/desktop/src/app/contrib/types.ts
+++ b/apps/desktop/src/app/contrib/types.ts
@@ -46,6 +46,7 @@ export type ChatActions = Pick<
| 'onRestoreToMessage'
| 'onRetryResume'
| 'onSteer'
+ | 'onSteerHidden'
| 'onSubmit'
| 'onThreadMessagesChange'
| 'onToggleSelectedPin'
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx
index 3e5fc7b3ef2..185e73588ef 100644
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@ -728,6 +728,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {
reloadFromMessage,
restoreToMessage,
steerPrompt,
+ injectHiddenPrompt,
submitText,
transcribeVoiceAudio
} = usePromptActions({
@@ -1136,6 +1137,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {
},
onRetryResume: sessionId => void resumeSession(sessionId, true),
onSteer: steerPrompt,
+ onSteerHidden: injectHiddenPrompt,
onSubmit: submitText,
onThreadMessagesChange: handleThreadMessagesChange,
onToggleSelectedPin: toggleSelectedPin,
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
index b82d28c0150..88283501fe8 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
@@ -822,6 +822,42 @@ export function usePromptActions({
[activeSessionIdRef, appendSessionTextMessage, requestGateway, selectedStoredSessionIdRef, updateSessionState]
)
+ // A hidden note that lands mid-turn must reach the model without becoming a
+ // user turn. session.steer injects it into the model's next tool result and
+ // records nothing in the transcript; a redirect would paint it as the user's
+ // own bubble and store it as one.
+ const injectHiddenPrompt = useCallback(
+ async (rawText: string): Promise<boolean> => {
+ const text = sanitizeComposerInput(rawText).trim()
+ const sessionId = activeSessionIdRef.current
+
+ if (!text || !sessionId) {
+ return false
+ }
+
+ const send = async (id: string): Promise<boolean> => {
+ const response = await requestGateway<SessionRedirectResponse>('session.steer', { session_id: id, text })
+
+ return response?.status === 'queued'
+ }
+
+ try {
+ const { result } = await withSessionNotFoundResume(sessionId, selectedStoredSessionIdRef.current, send, {
+ requestGateway,
+ onRecovered: recoveredId => {
+ activeSessionIdRef.current = recoveredId
+ setActiveSessionId(recoveredId)
+ }
+ })
+
+ return result
+ } catch {
+ return false
+ }
+ },
+ [activeSessionIdRef, requestGateway, selectedStoredSessionIdRef]
+ )
+
// After a durable rewind the surviving bubbles' cached rowIds are stale (the
// gateway re-inserted the kept prefix as new SQLite rows). Rebind them to the
// authoritative post-rewrite ids so the NEXT rewind/edit/regenerate doesn't
@@ -1161,6 +1197,7 @@ export function usePromptActions({
executeSlashCommand,
handleThreadMessagesChange,
handoffSession,
+ injectHiddenPrompt,
reloadFromMessage,
restoreToMessage,
redirectPrompt,
diff --git a/apps/desktop/src/components/assistant-ui/connector-tool.tsx b/apps/desktop/src/components/assistant-ui/connector-tool.tsx
index 97a13da06a8..55312fbae8f 100644
--- a/apps/desktop/src/components/assistant-ui/connector-tool.tsx
+++ b/apps/desktop/src/components/assistant-ui/connector-tool.tsx
@@ -4,7 +4,9 @@ import { useEffect, useMemo, useRef, useState } from 'react'
import { requestComposerSubmit } from '@/app/chat/composer/focus'
import { useSessionView } from '@/app/chat/session-view'
+import { isFirstBuildSession } from '@/app/contrib/handoff-receipt'
import { resolveSessionOwner } from '@/app/session/hooks/use-session-actions/utils'
+import { FirstBuildConnectorOffer } from '@/components/assistant-ui/first-build-connectors'
import { ToolFallback } from '@/components/assistant-ui/tool/fallback'
import { Button } from '@/components/ui/button'
import { ConnectorCard, type ConnectorCardCopy } from '@/components/ui/connector-card'
@@ -24,6 +26,7 @@ export function ConnectorTool(props: ToolCallMessagePartProps) {
const runtimeId = useStore(view.$runtimeId)
const storedId = useStore(view.$storedId)
const messages = useStore(view.$messages)
+ const firstBuild = isFirstBuildSession(storedId)
// One live card per offer. Every manage_connections call renders through
// here, but only ONE is the card the user acts on; the rest are settled
@@ -84,6 +87,19 @@ export function ConnectorTool(props: ToolCallMessagePartProps) {
}
const historical = liveId !== props.toolCallId
+ // A status call with no target list describes the whole catalog. That is an
+ // answer for the model, not an offer to the user: rendering it as rows put a
+ // Connect button on every app the gateway knows.
+ const input = recordOf(props.args)
+
+ const untargetedStatus =
+ props.toolName === 'manage_connections' &&
+ (input.action ?? 'status') === 'status' &&
+ !(Array.isArray(input.connectors) && input.connectors.length > 0)
+
+ // Neither kind of part owns the live offer, so neither resolves an owner or
+ // polls the gateway.
+ const inert = historical || untargetedStatus
const [owner, setOwner] = useState<{
storedId: string
@@ -92,8 +108,10 @@ export function ConnectorTool(props: ToolCallMessagePartProps) {
profile: string
} | null>(null)
+ const [ownerFailure, setOwnerFailure] = useState<string | null>(null)
+
useEffect(() => {
- if (!storedId || !runtimeId || historical) {
+ if (!storedId || !runtimeId || inert) {
return
}
@@ -115,13 +133,14 @@ export function ConnectorTool(props: ToolCallMessagePartProps) {
.catch(() => {
if (!cancelled) {
setOwner(null)
+ setOwnerFailure(`${storedId}:${runtimeId}`)
}
})
return () => {
cancelled = true
}
- }, [storedId, runtimeId, historical])
+ }, [storedId, runtimeId, inert])
const rows = connectionRows(props.args, props.result)
const signature = rows.map(row => row.connector).join('|')
const target = view.kind === 'tile' ? `tile:${storedId}` : 'main'
@@ -140,7 +159,7 @@ export function ConnectorTool(props: ToolCallMessagePartProps) {
}
const flow = useMemo(() => {
- if (historical || !runtimeId || !owner || owner.storedId !== storedId || owner.runtimeId !== runtimeId) {
+ if (firstBuild || inert || !runtimeId || !owner || owner.storedId !== storedId || owner.runtimeId !== runtimeId) {
return null
}
@@ -160,11 +179,10 @@ export function ConnectorTool(props: ToolCallMessagePartProps) {
`The user clicked Connect for ${connectorTitle(slug)} and the sign-in is open in their browser. Call manage_connections action="wait" connectors=["${slug}"] now and hold there until it reports connected. Do NOT call connect again — a second link cancels the one they are signing in with. Say nothing until wait returns.`
)
})
- }, [runtimeId, owner, storedId, signature, historical])
+ }, [runtimeId, owner, storedId, signature, inert, firstBuild])
const { t } = useI18n()
- // A result is a snapshot. Reopening a transcript only refreshes status; it
- // cannot mint links, open tabs or restart an abandoned authorization.
+ // Ordinary sessions require a click to begin authorization.
useEffect(() => {
if (!flow) {
return
@@ -178,12 +196,29 @@ export function ConnectorTool(props: ToolCallMessagePartProps) {
}
}, [flow, props.result])
- if (historical) {
+ if (inert) {
return <ToolFallback {...props} />
}
+ if (firstBuild && storedId && owner?.storedId === storedId && owner.runtimeId === runtimeId) {
+ return (
+ <FirstBuildConnectorOffer
+ connectionId={owner.connectionId}
+ part={props}
+ profile={owner.profile}
+ runtimeId={owner.runtimeId}
+ storedId={storedId}
+ target={view.kind === 'tile' ? `tile:${storedId}` : 'main'}
+ />
+ )
+ }
+
if (!flow) {
- return <p className="text-xs text-muted-foreground">{t.connectors.ownerMissing}</p>
+ return (
+ <p className="text-xs text-muted-foreground">
+ {ownerFailure === `${storedId}:${runtimeId}` ? t.connectors.ownerMissing : t.connectors.checking}
+ </p>
+ )
}
return (
diff --git a/apps/desktop/src/components/assistant-ui/first-build-connectors.tsx b/apps/desktop/src/components/assistant-ui/first-build-connectors.tsx
new file mode 100644
index 00000000000..a19552e28e3
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/first-build-connectors.tsx
@@ -0,0 +1,103 @@
+import { useStore } from '@nanostores/react'
+import { useEffect } from 'react'
+
+import { requestComposerSubmit } from '@/app/chat/composer/focus'
+import { useSessionView } from '@/app/chat/session-view'
+import { Button } from '@/components/ui/button'
+import { useI18n } from '@/i18n'
+import { connectorTitle, latestConnectorPart } from '@/lib/connector-tools'
+import {
+ $firstBuildConnections,
+ type FirstBuildConnectorPart,
+ flushFirstBuildNote,
+ openFirstBuildLinks,
+ watchFirstBuildRows
+} from '@/store/first-build-connectors'
+import { requestGatewayForAgent } from '@/store/gateway'
+
+interface FirstBuildConnectorOfferProps {
+ part: FirstBuildConnectorPart
+ storedId: string
+ runtimeId: string
+ connectionId: string | null
+ profile: string
+ target: string
+}
+
+export function FirstBuildConnectorOffer({
+ part,
+ storedId,
+ runtimeId,
+ connectionId,
+ profile,
+ target
+}: FirstBuildConnectorOfferProps) {
+ const connections = useStore($firstBuildConnections, { keys: [storedId] })
+ const view = useSessionView()
+ const busy = useStore(view.$busy)
+ const messages = useStore(view.$messages)
+ const newest = latestConnectorPart(messages)
+ const newestToolCallId = newest?.type === 'tool-call' ? newest.toolCallId : undefined
+ const pendingNote = connections[storedId]?.pendingNote
+ const { t } = useI18n()
+ const { toolCallId, toolName, args, result } = part
+
+ useEffect(() => {
+ void openFirstBuildLinks(
+ storedId,
+ { toolCallId, toolName, args, result },
+ { open: window.hermesDesktop?.openExternal ? url => window.hermesDesktop.openExternal(url) : undefined }
+ )
+ }, [storedId, toolCallId, toolName, args, result])
+
+ useEffect(() => {
+ flushFirstBuildNote(storedId, newestToolCallId, busy, text =>
+ requestComposerSubmit(text, { displayKind: 'hidden', target })
+ )
+ }, [storedId, newestToolCallId, busy, pendingNote, target])
+
+ useEffect(() => {
+ if (newestToolCallId !== toolCallId) {
+ return
+ }
+
+ return watchFirstBuildRows(storedId, runtimeId, { toolCallId, toolName, args, result }, (method, params) =>
+ requestGatewayForAgent(connectionId, profile, method, params, 45000)
+ )
+ }, [storedId, runtimeId, toolCallId, toolName, args, result, connectionId, profile, newestToolCallId])
+
+ return (
+ <div className="my-2 grid min-w-0 max-w-lg gap-3" data-connector-offer>
+ {connections[storedId]?.rows.map(row => (
+ <div className="flex items-center justify-between gap-3 text-sm" key={row.connector}>
+ <span>{connectorTitle(row.connector)}</span>
+ <span aria-live="polite" className="text-xs text-muted-foreground">
+ {row.phase === 'connected' ? (
+ <>
+ <span aria-hidden>✓ </span>
+ {t.connectors.connected}
+ </>
+ ) : row.phase === 'timeout' ? (
+ t.connectors.notConnected
+ ) : row.phase === 'error' ? (
+ row.error === 'unavailable' ? (
+ t.connectors.notAvailable
+ ) : (
+ t.connectors.statusError
+ )
+ ) : (
+ t.connectors.waitingSignIn
+ )}
+ </span>
+ {row.connectUrl && row.phase !== 'connected' && !window.hermesDesktop?.openExternal ? (
+ <Button asChild size="xs" variant="link">
+ <a href={row.connectUrl} rel="noreferrer" target="_blank">
+ {t.connectors.connect}
+ </a>
+ </Button>
+ ) : null}
+ </div>
+ ))}
+ </div>
+ )
+}
diff --git a/apps/desktop/src/components/onboarding-chat/options.tsx b/apps/desktop/src/components/onboarding-chat/options.tsx
index b9cfa022050..6fed826e969 100644
--- a/apps/desktop/src/components/onboarding-chat/options.tsx
+++ b/apps/desktop/src/components/onboarding-chat/options.tsx
@@ -3,11 +3,11 @@ import { Tip } from '@/components/ui/tooltip'
import { IS_MAC } from '@/lib/keybinds/combo'
import { cn } from '@/lib/utils'
-// Which live-catalog slugs to lead with, and in what order. The catalog is the
-// source of truth for WHAT can be connected — this is only a sort key for the
-// picker, so the apps most people use land in the first rows and the rest
-// stay reachable by search. A slug the catalog no longer carries is simply
-// not shown; a new one it gains is shown after these.
+// Which live-catalog slugs the first-run picker shows, and in what order. The
+// catalog is the source of truth for WHAT can be connected; this list picks the
+// few everyday apps out of it (D89). A slug the catalog no longer carries is
+// simply not shown, and a slug the catalog gains is not shown until it is
+// added here.
export const CONNECTOR_LEAD_ORDER = [
'gmail',
'googlecalendar',
@@ -30,11 +30,13 @@ export const CONNECTOR_LEAD_ORDER = [
// carries them for the agent's sake; the first-run picker leaves them out.
export const CONNECTOR_PICKER_HIDDEN = new Set(['discord', 'discordbot', 'microsoft_teams'])
-export function orderConnectorPicks<T extends { connector: string }>(rows: T[]): T[] {
+// A row the gateway marks `enabled: false` is a toolkit the deployment has
+// turned off; the agent cannot connect it, so the picker does not offer it.
+export function orderConnectorPicks<T extends { connector: string; enabled?: boolean }>(rows: T[]): T[] {
const rank = new Map(CONNECTOR_LEAD_ORDER.map((slug, index) => [slug, index]))
return rows
- .filter(row => !CONNECTOR_PICKER_HIDDEN.has(row.connector))
+ .filter(row => rank.has(row.connector) && row.enabled !== false && !CONNECTOR_PICKER_HIDDEN.has(row.connector))
.sort((a, b) => {
const ra = rank.get(a.connector) ?? Number.POSITIVE_INFINITY
const rb = rank.get(b.connector) ?? Number.POSITIVE_INFINITY
diff --git a/apps/desktop/src/components/onboarding-chat/setup-profile.ts b/apps/desktop/src/components/onboarding-chat/setup-profile.ts
index 4a4c15d7e07..40b92fc7f07 100644
--- a/apps/desktop/src/components/onboarding-chat/setup-profile.ts
+++ b/apps/desktop/src/components/onboarding-chat/setup-profile.ts
@@ -27,6 +27,8 @@ import { atom } from 'nanostores'
import type { HandoffReceipt } from '@/app/contrib/handoff-leg'
import { handoffReceiptKey, readHandoffReceipt } from '@/app/contrib/handoff-receipt'
import type { GatewayRequest } from '@/app/session/hooks/use-prompt-actions/utils'
+import { CONNECTOR_LEAD_ORDER } from '@/components/onboarding-chat/options'
+import { connectorTitle } from '@/lib/connector-tools'
import { activeGatewayConnectionId } from '@/store/gateway'
import { machineDescription } from '@/store/machine'
import type { OnboardingAnswers } from '@/store/onboarding-answers'
@@ -167,8 +169,9 @@ export function composeSetupSoul(): string {
}
/** The hidden runbook seeded into the first build's session — the work-side
- * half of the old single-chat script: no-auth first build, the permissions
- * note, and the live progress cards. */
+ * half of the old single-chat script: the permissions note, the live progress
+ * cards, and, when the user picked apps during setup, the connect-first
+ * opening. With no picks the first build stays account-free. */
export function buildFirstTaskRunbook(
task: string,
answers: OnboardingAnswers,
@@ -177,7 +180,10 @@ export function buildFirstTaskRunbook(
): string {
const name = (answers.name ?? '').trim()
const context = (answers.context ?? '').trim()
- const tools = (answers.connectors ?? []).filter(Boolean)
+ const tools = (answers.connectors ?? []).filter(slug => CONNECTOR_LEAD_ORDER.includes(slug))
+ // Machine setup needs no account anywhere; every other plan connects the
+ // picked apps before it does anything else (D85).
+ const connectFirst = tools.length > 0 && plan !== 'machine-setup'
return [
`You are Hermes. The user's welcome chat just opened this session so one task can have room to run: ${task.trim()}.`,
@@ -186,13 +192,15 @@ export function buildFirstTaskRunbook(
context
? `They already said what they are working on: ${context}. Let it shape your choices without re-asking.`
: '',
- tools.length
- ? `Apps they said they use: ${tools.join(', ')}. Some may already be connected from onboarding; check with manage_connections action="status" before assuming either way, and never require an unconnected one for this first build.`
+ tools.length && !connectFirst
+ ? `Apps they said they use: ${tools.map(connectorTitle).join(', ')}. Some may already be connected from onboarding; check with manage_connections action="status" before assuming either way, and never require an unconnected one for this first build.`
: '',
- 'Their next message is the go signal: really begin the work — plan briefly, then build (scaffold, research, first artifact).',
+ connectFirst
+ ? 'Their next message is the go signal. Before any plan and before any other tool, connect their apps as the CONNECT FIRST section says; the work itself starts the moment the wait returns or they tell you to start.'
+ : 'Their next message is the go signal: really begin the work — plan briefly, then build (scaffold, research, first artifact).',
"As you start, tell them in one short sentence: you'll ask for permissions as you go, and they can say no to anything or redirect you.",
- ...planRunbook(plan, pluginRoot),
- ...connectorRunbook(tools),
+ ...planRunbook(plan, pluginRoot, connectFirst),
+ ...(connectFirst ? connectFirstRunbook(tools) : []),
'While the work runs, place ::onboarding{step="progress" title="what you\'re doing"} as its own paragraph at the start of each status turn — the card shows the build breathing live. Keep the titles short and present-tense ("Scaffolding the project", "Wiring the reminder"). Emit each exactly like that, alone on its own line.',
'When the first pass of the build is DONE: end that turn with ::ask{question="Does this match what you wanted?" options="Looks right|Change something|Take it further"} alone as its own paragraph, emitted EXACTLY as written. Act on their pick immediately. One unreviewed first output is how a build reads as broken; the ask is how it reads as a collaboration.',
PLAIN_SPEECH
@@ -204,17 +212,22 @@ export function buildFirstTaskRunbook(
const NO_AUTH_RULE =
'CRITICAL: this first build must be finishable with NO external account or OAuth (no Gmail, no Slack, no Google sign-in) — connectors get wired only with their consent, and an app that is already connected may be used, one that is not may be offered. Everything else is fair game and the more visible the better: web research with the browser shown to the user as you work, scripts, computer use, a small app, a file-based tracker, a scheduled reminder, a generated page. If the idea needs an account that is not connected, build the no-auth core first and offer the connection as the next step. NEVER route around a connector: an unconnected Gmail is not a cue to install an IMAP client, ask for an app password, or find another way into the same account. The connector IS the way in; if they decline it, the app is out of this build.'
-/** The picks invite an optional connection, not a claim that an account is already linked. */
-function connectorRunbook(picks: string[]): string[] {
- if (picks.length === 0) {
- return []
- }
+/** The picks are gateway slugs the user chose during setup; connecting them is
+ * the session's first act, and the agent owns the wait (D85). The app, not the
+ * agent, opens the sign-ins and reports back with a hidden note. */
+function connectFirstRunbook(picks: string[]): string[] {
+ const named = picks.map(slug => `${slug} (${connectorTitle(slug)})`).join(', ')
return [
- `The user said they use these apps: ${picks.join(', ')}. These are real connector slugs. Offer to connect the ones useful for this task BEFORE the build starts, in your first turn, so the work can use them from the beginning — but keep the no-auth core moving and never require sign-in to finish it. If none of them help this task, say so in one line and move on; do not describe the catalog.`,
- 'Before you mention connecting anything, use manage_connections action="status" once. Anything already connected is yours to use for the task, with consent before reading private data. Match the rest against the returned catalog; never invent a connector slug or claim an unavailable app is supported. For the apps they agree to connect, make ONE action="connect" call carrying every slug at once (connectors=["gmail","googlecalendar"]) — the app renders one Connect card per app, side by side, and the user works through them; one call per app strands them clicking through a queue. Do not paste the authorization links into prose. Never call connect a second time for an app that already has a card: a new link cancels the one they are signing in with.',
- 'THE CARD IS THE ASK. After a status that shows an app unconnected, or after a connect, write ONE short line and END YOUR TURN — the user answers with the card’s buttons, not with text. Do not start work, do not call other tools, do not decide for them. Their click arrives as a hidden [connectors] message telling you exactly which manage_connections call to make next; follow it. When it says to wait, call action="wait" for that slug and hold: wait blocks until the authorization lands, so you never guess whether they are done. A timeout, declined consent or gateway outage means not connected, never an empty inbox. Say which apps remain unavailable and offer to continue without them. Never describe a gateway error as proof they need another Nous login.',
- 'Discover the connected app’s relevant tools with tool_search and use real results for the requested task. Never fabricate sample account data as if it came from a connector. Reading is separate from sending, deleting or scheduling: ask before those actions. No automatic daily brief or recurring job unless that is what the user asked for.'
+ `CONNECT FIRST. During setup the user picked these apps, given here as exact gateway slugs: ${named}. Your first action in this session, before any plan and before any other tool call, is ONE manage_connections call with action="connect" and connectors set to every one of those slugs. Do not call action="status" first; the slugs are exact and the catalog check is already done.`,
+ 'If every result comes back already active, there is nothing to wait for: begin the task at once.',
+ "The app opens every sign-in from that result in the user's browser and shows one row per app, so never paste the links. In the same turn say one short line: which apps are being connected and, in a clause each, what this task gets from each one. Then end the turn.",
+ 'Then call manage_connections action="wait" with the same slugs and timeout_seconds=120, and say nothing until it returns. If the wait comes back as pending because the links were minted moments ago, end your turn: the app sends a hidden note that begins with "[setup] links opened" once your turn ends and the sign-ins are open, and that note is your cue to call the same wait again. A note that arrives after you have already waited needs no reply.',
+ 'The user can start early. A message from them that begins with "Start with" or "Start without" names the apps that are connected and the ones they skipped; treat it as the go signal and begin with the connected apps only.',
+ 'When the wait returns with every app connected, begin the task at once. When it returns with apps still pending, stop and ask in one line: which apps did not connect, and whether they want you to continue without them or try connecting again (a fresh action="connect" mints new links). Wait for their answer. If they choose to continue without an app, build the version of the task that needs no account for that part and say in one line what the connection would have added.',
+ 'Account data comes from the connected apps first. Tools already signed in on this machine, like a logged-in gh, are fair to use when the task benefits; say so in one line when you do.',
+ "Discover a connected app's tools with tool_search and use real results for the task; never fabricate account data. Reading is separate from sending, deleting or scheduling: ask before those. No recurring job unless that is what they asked for.",
+ 'Make the result something they can open: a single HTML page when the idea allows it, and at least one real reading or action through a connected app.'
]
}
@@ -260,22 +273,22 @@ const pluginRunbook = (root: string) => [
/** The plan's own instructions, or the no-auth rule when the shape is the
* user's own idea. One switch so a new plan cannot half-land: adding a case
* here is what makes `plan="…"` mean anything at the other end. */
-function planRunbook(plan: HandoffPlan, pluginRoot: string): string[] {
+function planRunbook(plan: HandoffPlan, pluginRoot: string, connectFirst: boolean): string[] {
switch (plan) {
case 'machine-setup':
return machineSetupRunbook()
case 'plugin':
- // NO_AUTH_RULE still applies: a plugin that needs an API key on its
- // first run is the same dead end as any other first build that does.
+ // Without picks NO_AUTH_RULE still applies: a plugin that needs an API
+ // key on its first run is the same dead end as any other first build.
if (!pluginRoot) {
throw new Error('The desktop plugin folder is unavailable. Retry before starting the first build.')
}
- return [...pluginRunbook(pluginRoot), NO_AUTH_RULE]
+ return connectFirst ? pluginRunbook(pluginRoot) : [...pluginRunbook(pluginRoot), NO_AUTH_RULE]
default:
- return [NO_AUTH_RULE]
+ return connectFirst ? [] : [NO_AUTH_RULE]
}
}
@@ -309,7 +322,7 @@ export async function buildFirstTaskSeedMessages(
* follow are driven by the build's own progress (see first-build.ts), not by
* a schedule Setup has to remember to create. */
export function buildHandoffCompleteNote(task: string): string {
- return `[setup] handoff complete — "${task.trim()}" is now building in its own session, and the user is watching it there. Say ONE short line and then stop: you're around if they want a hand, and this chat stays where it is. Do not ask a question, do not offer a list, do not schedule anything.`
+ return `[setup] handoff complete — "${task.trim()}" is now building in its own session on the default profile, and the user is watching it there. The app is showing them a short tour of the profile rail and the sessions list right now, so do not describe either. Say ONE short line and then stop: you're around if they want a hand, and this chat stays where it is. Do not ask a question, do not offer a list, do not schedule anything.`
}
// ── gateway helpers (called from the wiring's kickoff + handoff effects) ─────
diff --git a/apps/desktop/src/components/onboarding-chat/signpost.ts b/apps/desktop/src/components/onboarding-chat/signpost.ts
index 261f0c0abc7..b04f1f3e5e6 100644
--- a/apps/desktop/src/components/onboarding-chat/signpost.ts
+++ b/apps/desktop/src/components/onboarding-chat/signpost.ts
@@ -1,44 +1,39 @@
/**
- * THE PARTING SIGNPOST — one lit moment, at the one moment it earns itself.
+ * THE HANDOFF TOUR — three steps, at the one moment the ground moves.
*
- * The handoff is the only point in the run where the ground moves under the
- * user: they were talking to Hermes on its own profile, and they land mid-build
- * in a session of their own. The chat they just spent five minutes in is still
- * there, one square away in the profile rail, and nothing on screen says so.
+ * The handoff is the only point in the run where the user changes profile
+ * without asking to: they were talking to Hermes on its own profile, and they
+ * land mid-build in a session of their own. Nothing on screen says where the
+ * welcome chat went, or that the sessions list they now see belongs to a
+ * different profile than the one they were in a moment ago.
*
- * So as they land, the rail lights up once. A single accent-lit step, not a
- * tour: the whole appeal of this flow is that it happens in conversation, and
- * spending that on a click-through at the last beat would be a poor trade.
- *
- * Skipped for the user who answered "I'll figure it out" — they were offered a
- * look around and declined, and this is the shape of a look around. Their
- * version of this is a line in the chat (see the runbook's step 4).
+ * The guide cannot narrate this itself: the tour bridge only paints for the
+ * session the user is looking at, and after the handoff the guide is a
+ * background session (desktop AGENTS.md: offer, don't hijack). So the app runs
+ * the same three steps the guide would have asked for, in the user's language,
+ * and the guide's one line in its own chat says nothing about them.
*/
+import { translateNow } from '@/i18n'
-import { type ChatMessage, chatMessageText } from '@/lib/chat-messages'
-import { TOUR_OPTIONS } from '@/store/onboarding-script'
-
-/** The rail's tour handle (profile-switcher.tsx). `data-tour` rather than the
- * `data-slot` beside it because only the former is identity to
- * collectTourTargets — so this is the same selector the model gets back when
- * it scans for targets, not a private one this file made up. */
+/** Tour handles (`data-tour`), the same selectors the model gets back from a
+ * targets scan, so a curated step and a model-driven one point at one thing. */
const RAIL = '[data-tour="profile-rail"]'
-
-/** Did they wave off the look around? Read from the guide transcript, because
- * the pick IS a user turn there and the option text is pinned by the script
- * (that is what TOUR_OPTIONS is for — both sides read the same constant). */
-export function declinedLookAround(messages: ChatMessage[]): boolean {
- return messages.some(message => message.role === 'user' && chatMessageText(message).trim() === TOUR_OPTIONS.none)
-}
+const SESSIONS = '[data-tour="sessions-sidebar"]'
/** The rail mounts a render or two after the handoff swaps profiles, so wait
* for the node rather than firing into an empty DOM (the engine would return
* a no-match and the moment would pass silently). Gives up quietly. */
-async function waitForRail(timeoutMs = 6000): Promise<boolean> {
+async function waitFor(selector: string, timeoutMs = 6000): Promise<boolean> {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
- if (document.querySelector(RAIL)) {
+ const visible = [...document.querySelectorAll(selector)].some(node => {
+ const { width, height } = node.getBoundingClientRect()
+
+ return width > 0 && height > 0 && !node.closest('[data-pane-hidden]')
+ })
+
+ if (visible) {
return true
}
@@ -48,23 +43,24 @@ async function waitForRail(timeoutMs = 6000): Promise<boolean> {
return false
}
-/** Light the rail with the parting line. Never throws, never blocks the
- * handoff — this is the nicety at the end, not part of the machinery. */
-export async function showProfileSignpost(): Promise<void> {
- if (!(await waitForRail())) {
+/** Run the handoff tour. Never throws, never blocks the handoff. */
+export async function showHandoffTour(): Promise<void> {
+ if (!(await waitFor(RAIL))) {
return
}
+ const sessionsVisible = await waitFor(SESSIONS, 1500)
+ const copy = (key: string) => translateNow(`handoffTour.${key}`)
// Imported here, not at the top: this module is reachable from the boot path
// through the handoff hook, and driver.js plus its stylesheet are exactly
// what run-tour.ts keeps off it.
- const { showTourStep } = await import('@/lib/tour')
+ const { startTour } = await import('@/lib/tour')
- await showTourStep({
- accent: true,
- selector: RAIL,
- side: 'right',
- text: "You're in your own workspace now, and this is where the profiles live. The chat we just had is still in there — come back to it whenever you want a hand.",
- title: 'Hermes is still next door'
- })
+ await startTour([
+ { accent: true, selector: RAIL, side: 'right', text: copy('profileText'), title: copy('profileTitle') },
+ ...(sessionsVisible
+ ? [{ selector: SESSIONS, side: 'right' as const, text: copy('sessionsText'), title: copy('sessionsTitle') }]
+ : []),
+ { accent: true, selector: RAIL, side: 'right', text: copy('stayText'), title: copy('stayTitle') }
+ ])
}
diff --git a/apps/desktop/src/components/onboarding-chat/start.tsx b/apps/desktop/src/components/onboarding-chat/start.tsx
new file mode 100644
index 00000000000..08450fa12c9
--- /dev/null
+++ b/apps/desktop/src/components/onboarding-chat/start.tsx
@@ -0,0 +1,52 @@
+import { useStore } from '@nanostores/react'
+import { computed } from 'nanostores'
+import { useMemo } from 'react'
+
+import { requestComposerSubmit } from '@/app/chat/composer/focus'
+import { useSessionView } from '@/app/chat/session-view'
+import { isFirstBuildSession } from '@/app/contrib/handoff-receipt'
+import { Button } from '@/components/ui/button'
+import { useI18n } from '@/i18n'
+import { latestConnectorPart } from '@/lib/connector-tools'
+import { canStartWithConnections } from '@/lib/first-build-start'
+import { $firstBuildConnections, startFirstBuild } from '@/store/first-build-connectors'
+
+export function OnboardingStart() {
+ const { t } = useI18n()
+ const view = useSessionView()
+ const storedId = useStore(view.$storedId)
+ const $latest = useMemo(() => computed(view.$messages, latestConnectorPart), [view.$messages])
+ const latest = useStore($latest)
+ const connections = useStore($firstBuildConnections, { keys: [storedId ?? ''] })
+ const state = storedId ? connections[storedId] : undefined
+
+ if (
+ !storedId ||
+ !isFirstBuildSession(storedId) ||
+ !state ||
+ state.started ||
+ latest?.type !== 'tool-call' ||
+ state.toolCallId !== latest.toolCallId ||
+ !canStartWithConnections(latest)
+ ) {
+ return null
+ }
+
+ const count = state.rows.filter(row => row.phase === 'connected').length
+
+ return (
+ <Button
+ onClick={() =>
+ startFirstBuild(storedId, text =>
+ requestComposerSubmit(text, {
+ target: view.kind === 'tile' ? `tile:${storedId}` : 'main'
+ })
+ )
+ }
+ size="xs"
+ variant="secondary"
+ >
+ {count ? t.connectors.startWith(count) : t.connectors.startWithout}
+ </Button>
+ )
+}
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index fb132ebd140..ad7bf69067d 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -11,6 +11,12 @@ export const en: Translations = {
retry: 'Try again',
grant: 'Reconnect',
connected: 'Connected',
+ checking: 'Checking your apps…',
+ waitingSignIn: 'Waiting for you to finish signing in…',
+ notConnected: "Didn't connect",
+ notAvailable: 'Not available',
+ startWith: count => `Start the task with ${count} ${count === 1 ? 'app' : 'apps'} connected`,
+ startWithout: 'Start without connections',
skipped: 'Skipped',
disabled: 'Unavailable',
failed: 'Could not connect',
@@ -2842,6 +2848,7 @@ export const en: Translations = {
queuedPaused: count => `${count} Queued — paused`,
attachmentOnly: 'Attachment-only turn',
emptyTurn: 'Empty turn',
+ hiddenQueued: 'Setup note',
attachments: count => `${count} attachment${count === 1 ? '' : 's'}`,
editingInComposer: 'Editing in composer',
editingQueuedInComposer: 'Editing queued turn in composer',
@@ -3167,6 +3174,16 @@ export const en: Translations = {
}
},
+ handoffTour: {
+ profileTitle: 'Your first task runs on the default profile',
+ profileText:
+ 'This rail switches profiles. The one lit up now is default, where the task session lives. The other one is the setup profile, where the welcome chat lives.',
+ sessionsTitle: 'Each profile keeps its own sessions',
+ sessionsText:
+ 'This list belongs to the default profile. New session starts one on whichever profile is selected. Switch profiles on the rail and the list changes with it.',
+ stayTitle: 'Hermes is one click away',
+ stayText: 'Switch to the setup profile and open Welcome to Hermes whenever you want a hand. It stays there.'
+ },
guidedGreeting: {
line: "Hey, come on in. I'm Hermes. Give me two minutes to set the place up around you, then we'll put me to work on something you actually want done.\n\nFirst though, what should I call you?",
nameSuggestion: (name: string) => `(I can also just call you ${name}, if you prefer.)`
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index a93955ddffd..2bd34420174 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -59,6 +59,12 @@ export interface Translations {
retry: string
grant: string
connected: string
+ checking: string
+ waitingSignIn: string
+ notConnected: string
+ notAvailable: string
+ startWith: (count: number) => string
+ startWithout: string
skipped: string
disabled: string
failed: string
@@ -2433,6 +2439,7 @@ export interface Translations {
queuedPaused: (count: number) => string
attachmentOnly: string
emptyTurn: string
+ hiddenQueued: string
attachments: (count: number) => string
editingInComposer: string
editingQueuedInComposer: string
@@ -2730,6 +2737,14 @@ export interface Translations {
* model is told to speak the user's language from its first real turn, and
* an English opener above a Japanese reply reads as two different agents.
* `nameSuggestion` offers the OS account name as a default. */
+ handoffTour: {
+ profileTitle: string
+ profileText: string
+ sessionsTitle: string
+ sessionsText: string
+ stayTitle: string
+ stayText: string
+ }
guidedGreeting: {
line: string
nameSuggestion: (name: string) => string
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 0e553215a05..fcce24b1871 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -1,8 +1,8 @@
import { defineFieldCopy } from '@/app/settings/field-copy'
-import type { Translations } from './types'
+import { defineLocale } from './define-locale'
-export const zh: Translations = {
+export const zh = defineLocale({
connectors: {
title: '连接你的应用',
connect: '连接',
@@ -4299,4 +4299,4 @@ export const zh: Translations = {
toggle: open => `${open ? '显示' : '隐藏'}侧边栏`
}
}
-}
+})
diff --git a/apps/desktop/src/lib/connector-tools.ts b/apps/desktop/src/lib/connector-tools.ts
index 1e6b3256072..ad661c292d6 100644
--- a/apps/desktop/src/lib/connector-tools.ts
+++ b/apps/desktop/src/lib/connector-tools.ts
@@ -1,6 +1,29 @@
import { isRecord } from '@assistant-ui/core/internal'
import type { ToolCallMessagePart } from '@assistant-ui/react'
+import type { ChatMessage } from '@/lib/chat-messages'
+
+export function latestConnectorPart(messages: ChatMessage[]) {
+ return messages
+ .flatMap(message => message.parts)
+ .filter(part => {
+ if (part.type !== 'tool-call') {
+ return false
+ }
+
+ if (part.toolName === 'manage_connections') {
+ const input = recordOf(part.args)
+
+ return (
+ (input.action ?? 'status') !== 'status' || (Array.isArray(input.connectors) && input.connectors.length > 0)
+ )
+ }
+
+ return connectorCalls(part.toolName, part.args).length > 0
+ })
+ .at(-1)
+}
+
/** Connector names/results as presentation data, never authorization. */
export interface ConnectorRow {
connector: string
@@ -38,10 +61,13 @@ const TITLES: ConnectorTitles = {
gmail: 'Gmail',
googlecalendar: 'Google Calendar',
googledrive: 'Google Drive',
+ googledocs: 'Google Docs',
slack: 'Slack',
github: 'GitHub',
notion: 'Notion',
linear: 'Linear',
+ jira: 'Jira',
+ todoist: 'Todoist',
figma: 'Figma',
discord: 'Discord',
stripe_mcp: 'Stripe',
diff --git a/apps/desktop/src/lib/first-build-start.ts b/apps/desktop/src/lib/first-build-start.ts
new file mode 100644
index 00000000000..c953422656c
--- /dev/null
+++ b/apps/desktop/src/lib/first-build-start.ts
@@ -0,0 +1,40 @@
+import type { ChatMessagePart } from '@/lib/chat-messages'
+import { connectorAuthorizationUrl, connectorTitle, recordOf } from '@/lib/connector-tools'
+import type { ConnectorFlowRow } from '@/store/connector-flow'
+
+function naturalJoin(names: string[]): string {
+ return names.length < 2 ? names.join('') : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`
+}
+
+export function buildConnectionStartMessage(rows: readonly ConnectorFlowRow[]): string {
+ const connected = rows.filter(row => row.phase === 'connected').map(row => connectorTitle(row.connector))
+ const skipped = rows.filter(row => row.phase !== 'connected').map(row => connectorTitle(row.connector))
+
+ return (
+ (connected.length ? `Start with ${naturalJoin(connected)} connected.` : 'Start without connections.') +
+ (skipped.length ? ` I skipped ${naturalJoin(skipped)}.` : '')
+ )
+}
+
+export function canStartWithConnections(part: ChatMessagePart): boolean {
+ if (part.type !== 'tool-call' || part.toolName !== 'manage_connections') {
+ return false
+ }
+
+ const action = recordOf(part.args).action
+ const output = recordOf(part.result)
+
+ if (action === 'wait') {
+ return part.result === undefined || output.status === 'pending'
+ }
+
+ return (
+ action === 'connect' &&
+ Array.isArray(output.results) &&
+ output.results.some(item => {
+ const entry = recordOf(item)
+
+ return entry.status === 'initiated' && connectorAuthorizationUrl(entry.connect_url) !== null
+ })
+ )
+}
diff --git a/apps/desktop/src/store/composer-queue.test.ts b/apps/desktop/src/store/composer-queue.test.ts
index 7e7d0940ee0..f5ebd9124d0 100644
--- a/apps/desktop/src/store/composer-queue.test.ts
+++ b/apps/desktop/src/store/composer-queue.test.ts
@@ -260,3 +260,19 @@ describe('parked queue sessions', () => {
expect(isQueueParked('rt-new')).toBe(false)
})
})
+
+describe('hidden entries', () => {
+ beforeEach(() => {
+ clearQueuedPrompts('hidden-session')
+ })
+
+ it('keeps the hidden kind on a queued note and leaves visible entries without one', () => {
+ enqueueQueuedPrompt('hidden-session', { text: '[setup] links opened', attachments: [], displayKind: 'hidden' })
+ enqueueQueuedPrompt('hidden-session', { text: 'Start without connections.', attachments: [] })
+
+ expect(getQueuedPrompts('hidden-session').map(({ text, displayKind }) => ({ text, displayKind }))).toEqual([
+ { text: '[setup] links opened', displayKind: 'hidden' },
+ { text: 'Start without connections.', displayKind: undefined }
+ ])
+ })
+})
diff --git a/apps/desktop/src/store/composer-queue.ts b/apps/desktop/src/store/composer-queue.ts
index d53edca1d36..f51828f87d0 100644
--- a/apps/desktop/src/store/composer-queue.ts
+++ b/apps/desktop/src/store/composer-queue.ts
@@ -11,6 +11,9 @@ export interface QueuedPromptEntry {
* text the agent receives. A queued `/skill` invocation carries the whole
* expanded skill body as `text` — the UI shows the invocation instead. */
displayText?: string
+ /** A hidden note (a setup line for the model) parked while the turn ran. The panel
+ * shows a neutral label and the drain submits it hidden again. */
+ displayKind?: 'hidden'
attachments: ComposerAttachment[]
queuedAt: number
}
@@ -125,7 +128,7 @@ export const getQueuedPrompts = (key: string | null | undefined): QueuedPromptEn
export const enqueueQueuedPrompt = (
key: string | null | undefined,
- payload: { text: string; attachments: ComposerAttachment[]; displayText?: string }
+ payload: { text: string; attachments: ComposerAttachment[]; displayText?: string; displayKind?: 'hidden' }
): null | QueuedPromptEntry => {
const sid = sidOf(key)
@@ -137,6 +140,7 @@ export const enqueueQueuedPrompt = (
id: nextId(),
text: payload.text,
...(payload.displayText ? { displayText: payload.displayText } : {}),
+ ...(payload.displayKind ? { displayKind: payload.displayKind } : {}),
attachments: cloneAttachments(payload.attachments),
queuedAt: Date.now()
}
diff --git a/apps/desktop/src/store/connector-catalog.ts b/apps/desktop/src/store/connector-catalog.ts
index 702891ef765..34be783766a 100644
--- a/apps/desktop/src/store/connector-catalog.ts
+++ b/apps/desktop/src/store/connector-catalog.ts
@@ -8,9 +8,12 @@
* actually there, through the same session-owned RPC the connector cards
* use, so the picker can only ever offer what can be connected.
*
- * `available: false` (toolset off, signed out) and a failed request both
- * resolve to `null` rows — the caller decides what to show; there is no
- * fallback list here, because a fallback is how the drift started.
+ * `available: false` (toolset off, signed out), a failed request, and a
+ * request that takes longer than 15 s all resolve to `unavailable`; the caller
+ * decides what to show. There is no fallback list here, because a fallback is
+ * how the drift started. Missing session ids resolve to `unavailable` too,
+ * and the probe runs once they arrive, so the card never waits on a request
+ * that was never sent.
*/
import { useEffect, useState } from 'react'
@@ -21,16 +24,22 @@ import { $activeGatewayProfile } from '@/store/profile'
import { assertSessionOwnerResolved } from '@/store/session-owner-resolution'
import { isSessionOwnerRoute } from '@/store/session-request-router'
-export type ConnectorCatalog = { status: 'loading' } | { status: 'ready'; rows: ConnectorRow[] } | { status: 'unavailable' }
+export type ConnectorCatalog =
+ { status: 'loading' } | { status: 'ready'; rows: ConnectorRow[] } | { status: 'unavailable' }
export function useConnectorCatalog(storedId: null | string, runtimeId: null | string): ConnectorCatalog {
- const [catalog, setCatalog] = useState<ConnectorCatalog>({ status: 'loading' })
+ const [catalog, setCatalog] = useState<ConnectorCatalog>(() =>
+ storedId && runtimeId ? { status: 'loading' } : { status: 'unavailable' }
+ )
useEffect(() => {
if (!storedId || !runtimeId) {
+ setCatalog({ status: 'unavailable' })
+
return
}
+ setCatalog({ status: 'loading' })
let cancelled = false
const ambientProfile = $activeGatewayProfile.get()
@@ -45,7 +54,8 @@ export function useConnectorCatalog(storedId: null | string, runtimeId: null | s
connectionId,
profile,
'connectors.list',
- { session_id: runtimeId }
+ { session_id: runtimeId },
+ 15000
)
})
.then(response => {
diff --git a/apps/desktop/src/store/first-build-connectors.ts b/apps/desktop/src/store/first-build-connectors.ts
new file mode 100644
index 00000000000..e215ce5708a
--- /dev/null
+++ b/apps/desktop/src/store/first-build-connectors.ts
@@ -0,0 +1,277 @@
+import type { ToolCallMessagePart } from '@assistant-ui/react'
+import { map } from 'nanostores'
+
+import { endFirstBuildConnect, isFirstBuildSession } from '@/app/contrib/handoff-receipt'
+import {
+ connectionRows,
+ connectorAuthorizationUrl,
+ type ConnectorRow,
+ connectorText,
+ recordOf
+} from '@/lib/connector-tools'
+import { buildConnectionStartMessage, canStartWithConnections } from '@/lib/first-build-start'
+import { readKey, writeKey } from '@/lib/storage'
+import type { ConnectorFlowDeps, ConnectorFlowRow } from '@/store/connector-flow'
+
+export type FirstBuildConnectorPart = Pick<ToolCallMessagePart, 'toolCallId' | 'toolName' | 'args' | 'result'>
+
+export interface FirstBuildConnectorRow extends ConnectorFlowRow {
+ connectUrl?: string
+}
+
+export interface FirstBuildConnectorState {
+ toolCallId: string
+ rows: FirstBuildConnectorRow[]
+ started: boolean
+ /** The "[setup] links opened" note, held until the session is idle. A submit
+ * while the model's turn runs is rejected by the gateway, and the model
+ * usually calls wait in that same turn, so the note is a fallback cue. */
+ pendingNote?: string
+}
+
+export const $firstBuildConnections = map<Record<string, FirstBuildConnectorState>>({})
+
+interface OpenLinksDeps {
+ open?: (url: string) => Promise<void>
+}
+
+export async function openFirstBuildLinks(storedId: string, part: FirstBuildConnectorPart, deps: OpenLinksDeps) {
+ if (
+ !isFirstBuildSession(storedId) ||
+ part.toolName !== 'manage_connections' ||
+ !['connect', 'reconnect'].includes(String(recordOf(part.args).action))
+ ) {
+ return
+ }
+
+ const output = recordOf(part.result)
+
+ if (!Array.isArray(output.results)) {
+ return
+ }
+
+ const entries = output.results.map(recordOf)
+ const previous = $firstBuildConnections.get()[storedId]
+
+ const rows = connectionRows(part.args, part.result).map((seed): FirstBuildConnectorRow => {
+ const existing = previous?.rows.find(row => row.connector === seed.connector)
+ const entry = entries.find(row => row.connector === seed.connector)
+ const connectUrl = entry?.status === 'initiated' ? connectorAuthorizationUrl(entry.connect_url) : null
+
+ return {
+ ...seed,
+ ...existing,
+ phase:
+ entry?.status === 'active'
+ ? 'connected'
+ : connectUrl && previous?.toolCallId !== part.toolCallId
+ ? 'waiting'
+ : (existing?.phase ?? 'idle'),
+ connectUrl: connectUrl ?? undefined
+ }
+ })
+
+ $firstBuildConnections.setKey(storedId, {
+ toolCallId: part.toolCallId,
+ rows,
+ started: previous?.started ?? readKey(`hermes.onboarding.started.v1.${storedId}`) === '1'
+ })
+
+ const links = entries.flatMap(entry => {
+ const url = entry.status === 'initiated' ? connectorAuthorizationUrl(entry.connect_url) : null
+ const connector = connectorText(entry.connector)
+
+ return url && connector !== undefined ? [{ connector, url }] : []
+ })
+
+ const key = `hermes.onboarding.links-opened.v1.${part.toolCallId}`
+
+ if (!deps.open || !links.length || readKey(key) === '1') {
+ return
+ }
+
+ // Claim before opening so concurrent renders and relaunches cannot open the batch twice.
+ writeKey(key, '1')
+ const open = deps.open
+ const outcomes = await Promise.allSettled(links.map(link => open(link.url)))
+ const opened = links.filter((_link, index) => outcomes[index].status === 'fulfilled')
+
+ const state = $firstBuildConnections.get()[storedId]
+
+ if (opened.length && state?.toolCallId === part.toolCallId) {
+ $firstBuildConnections.setKey(storedId, {
+ ...state,
+ pendingNote: `[setup] links opened for ${opened.map(link => link.connector).join(', ')}`
+ })
+ }
+}
+
+/** Deliver the held note once the session is idle, if the connect that minted
+ * the links is still the newest connector part. A newer part means the model
+ * already moved on (it called wait itself), and the note would only confuse it. */
+export function flushFirstBuildNote(
+ storedId: string,
+ newestToolCallId: string | undefined,
+ busy: boolean,
+ submit: (text: string) => boolean
+): void {
+ const state = $firstBuildConnections.get()[storedId]
+
+ if (!state?.pendingNote || busy) {
+ return
+ }
+
+ if (!isFirstBuildSession(storedId) || newestToolCallId !== state.toolCallId || submit(state.pendingNote)) {
+ $firstBuildConnections.setKey(storedId, { ...state, pendingNote: undefined })
+ }
+}
+
+export function watchFirstBuildRows(
+ storedId: string,
+ runtimeId: string,
+ part: FirstBuildConnectorPart,
+ request: ConnectorFlowDeps['request']
+) {
+ const action = recordOf(part.args).action
+
+ if (
+ !isFirstBuildSession(storedId) ||
+ part.toolName !== 'manage_connections' ||
+ (action !== 'wait' && !(action === 'connect' && canStartWithConnections({ ...part, type: 'tool-call' })))
+ ) {
+ return
+ }
+
+ const output = recordOf(part.result)
+ const polling = action === 'connect' || part.result === undefined || output.status === 'pending'
+
+ if (action === 'wait' && ['connected', 'timeout', 'interrupted'].includes(String(output.status))) {
+ endFirstBuildConnect(storedId)
+ }
+
+ const connected = new Set(
+ (Array.isArray(output.connectors) ? output.connectors : []).flatMap(item => {
+ const entry = recordOf(item)
+ const slug = connectorText(item) ?? connectorText(entry.connector)
+
+ return slug !== undefined && entry.connected !== false ? [slug] : []
+ })
+ )
+
+ const pending = new Set(Array.isArray(output.pending) ? output.pending : [])
+ const previous = $firstBuildConnections.get()[storedId]
+
+ const rows = connectionRows(part.args, part.result).map((seed): FirstBuildConnectorRow => {
+ const existing = previous?.rows.find(row => row.connector === seed.connector)
+ let phase = existing?.phase ?? 'waiting'
+
+ if (output.status !== 'interrupted') {
+ if (connected.has(seed.connector)) {
+ phase = 'connected'
+ } else if (output.status === 'timeout' && pending.has(seed.connector)) {
+ phase = 'timeout'
+ } else if (polling && phase !== 'connected') {
+ phase = 'waiting'
+ }
+ }
+
+ return { ...seed, ...existing, phase }
+ })
+
+ $firstBuildConnections.setKey(storedId, {
+ toolCallId: part.toolCallId,
+ rows,
+ started: previous?.started ?? readKey(`hermes.onboarding.started.v1.${storedId}`) === '1'
+ })
+
+ if (!polling) {
+ return
+ }
+
+ let cancelled = false
+ let failures = 0
+ const deadline = Date.now() + 150000
+ let timer: ReturnType<typeof setTimeout> | undefined
+
+ const current = () => {
+ const state = $firstBuildConnections.get()[storedId]
+
+ return (
+ !cancelled &&
+ failures < 3 &&
+ Date.now() < deadline &&
+ isFirstBuildSession(storedId) &&
+ !state?.started &&
+ state?.toolCallId === part.toolCallId
+ )
+ }
+
+ const poll = async () => {
+ if (!current()) {
+ return
+ }
+
+ try {
+ const result = await request<{ available: boolean; connectors: ConnectorRow[] }>('connectors.list', {
+ session_id: runtimeId
+ })
+
+ if (!current()) {
+ return
+ }
+
+ const state = $firstBuildConnections.get()[storedId]
+
+ const rows = state.rows.map((row): FirstBuildConnectorRow => {
+ const live = result.connectors.find(item => item.connector === row.connector)
+
+ if (!result.available || !live || live.enabled === false) {
+ return row.phase === 'connected' ? row : { ...row, enabled: false, phase: 'error', error: 'unavailable' }
+ }
+
+ return { ...row, ...live, phase: live.connected ? 'connected' : 'waiting', error: undefined }
+ })
+
+ $firstBuildConnections.setKey(storedId, { ...state, rows })
+ failures = 0
+ } catch {
+ if (!current()) {
+ return
+ }
+
+ const state = $firstBuildConnections.get()[storedId]
+ $firstBuildConnections.setKey(storedId, {
+ ...state,
+ rows: state.rows.map(row => (row.phase === 'connected' ? row : { ...row, phase: 'error', error: 'status' }))
+ })
+ failures += 1
+ }
+
+ if (current()) {
+ timer = setTimeout(() => void poll(), 2000)
+ }
+ }
+
+ void poll()
+
+ return () => {
+ cancelled = true
+ clearTimeout(timer)
+ }
+}
+
+/** A true submit result means the composer owns delivery through send, steer or queue. */
+export function startFirstBuild(storedId: string, submit: (text: string) => boolean): void {
+ const state = $firstBuildConnections.get()[storedId]
+ const key = `hermes.onboarding.started.v1.${storedId}`
+
+ if (!isFirstBuildSession(storedId) || !state || state.started || readKey(key) === '1') {
+ return
+ }
+
+ if (submit(buildConnectionStartMessage(state.rows))) {
+ writeKey(key, '1')
+ endFirstBuildConnect(storedId)
+ $firstBuildConnections.setKey(storedId, { ...state, started: true })
+ }
+}