@yuriai/web 0.1.14 → 0.1.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AgentAvatar-BsXXkno4.js → AgentAvatar-DPBeg3oL.js} +1 -1
- package/dist/assets/{AssistantView-DOi4K931.js → AssistantView-CAguYF82.js} +3 -3
- package/dist/assets/{DiagramView-AX_WR3eG.js → DiagramView-CxbdRsck.js} +1 -1
- package/dist/assets/{FadeInOnReveal-CJXal58M.js → FadeInOnReveal-Cx0k6XUX.js} +1 -1
- package/dist/assets/{Icon-CZFN8X-2.js → Icon-tuli5r38.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-ysZN5rfI.js → ImageLoadingPlaceholder-Bb5so0Of.js} +1 -1
- package/dist/assets/{LoadingImage-meArDBtS.js → LoadingImage-C6L95rT6.js} +1 -1
- package/dist/assets/{MarkdownRenderer-fC11logG.js → MarkdownRenderer-DbcP3Tbs.js} +2 -2
- package/dist/assets/{MarkdownRendererImpl-A0x9lifL.js → MarkdownRendererImpl-MfzVEFfK.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-Camlm3Ev.js → MarkstreamRendererImpl-CYOx7Er6.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-BkqkecBf.js → MobileDetailNavigation-inXvOHPi.js} +1 -1
- package/dist/assets/MobileShareBridge-Byo5PmXR.js +4 -0
- package/dist/assets/{MobileTabPageHeader-Bv9VftUT.js → MobileTabPageHeader-BQU7lzpw.js} +1 -1
- package/dist/assets/{MultiRunWindow-CHK4pv4L.js → MultiRunWindow-BlKX9FRf.js} +1 -1
- package/dist/assets/{OnboardingScreen-P4-mX2Oa.js → OnboardingScreen-DVmBX2U1.js} +1 -1
- package/dist/assets/{OverlayScrollbar-DLRRQ8xw.js → OverlayScrollbar-D5nUzsru.js} +1 -1
- package/dist/assets/{SettingsView-cT3bPM_E.js → SettingsView-CSS7wNYH.js} +1 -1
- package/dist/assets/{SettingsWindow-CZRLuT9-.js → SettingsWindow-D6sE8iUc.js} +1 -1
- package/dist/assets/{TerminalView-DqcyqVjS.js → TerminalView-D2H7kxHo.js} +1 -1
- package/dist/assets/{ToolOutputDialog-GLlq9-W6.js → ToolOutputDialog-CZ3VVPI6.js} +1 -1
- package/dist/assets/{YuriLogo-vNMmMKxV.js → YuriLogo-lTu65FqY.js} +1 -1
- package/dist/assets/{appThemeRegistry-B6pQ8vzc.js → appThemeRegistry-CClXFBev.js} +1 -1
- package/dist/assets/{button-CcMfow51.js → button-BYnYoCZy.js} +1 -1
- package/dist/assets/{capgoAdapter-Bb0fZtdX.js → capgoAdapter-C8LWpfj0.js} +1 -1
- package/dist/assets/{collapsible-BiSNWpgZ.js → collapsible-DZhQ_5lo.js} +1 -1
- package/dist/assets/{diagram-CO4NSnCB.js → diagram-CJZ0URNS.js} +1 -1
- package/dist/assets/{dialog-CCD3bivZ.js → dialog-nRZ4nWn0.js} +1 -1
- package/dist/assets/{dropdown-menu.styles-BJ80_XAj.js → dropdown-menu.styles-Z2jL8P90.js} +1 -1
- package/dist/assets/{es-Cu6zoTXv.js → es-DKMfE2g4.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-3h_vyEnU.js → fileMentionTouchSelection-BieboY85.js} +1 -1
- package/dist/assets/{fr-DA4Apf6C.js → fr-DeBe3ouU.js} +1 -1
- package/dist/assets/{gitApi-kzG0If3z.js → gitApi-DC820Jfy.js} +1 -1
- package/dist/assets/{input-BvqIFDJg.js → input-Ctn0g9vd.js} +1 -1
- package/dist/assets/{insertionBoundaries-CrivVfew.js → insertionBoundaries-D07Y7wWF.js} +1 -1
- package/dist/assets/{ja-DHQdrjZd.js → ja-BesmOdJA.js} +1 -1
- package/dist/assets/{ko-DbAl47mv.js → ko-C00DHDrX.js} +1 -1
- package/dist/assets/{main-Hlu0IB1K.js → main-BlhgRbh6.js} +2 -2
- package/dist/assets/{main-BIyBucv-.js → main-MSyLxAJz.js} +4 -4
- package/dist/assets/{markdownHeightCache-BSSU7Bxn.js → markdownHeightCache-qOdEJNXq.js} +1 -1
- package/dist/assets/{mcpQueries-DVSGJdEJ.js → mcpQueries-CduS3cJO.js} +1 -1
- package/dist/assets/{miniChat-D6JPgsqw.js → miniChat-NFM4xI9m.js} +2 -2
- package/dist/assets/{mobile-DDuy4pcy.js → mobile-DRtQrc9q.js} +2 -2
- package/dist/assets/{mobileBackNavigation-CeGcEoY2.js → mobileBackNavigation-CCWbuOBM.js} +1 -1
- package/dist/assets/{multirun-Brs9nl_V.js → multirun-Dbx7Z6O4.js} +1 -1
- package/dist/assets/{native-config-D0rnpJR8.js → native-config-DAksnjPm.js} +1 -1
- package/dist/assets/{pl-CogXecG6.js → pl-DjFYuP3K.js} +1 -1
- package/dist/assets/{projectMeta-N7IrdLdy.js → projectMeta-BtT4i96U.js} +1 -1
- package/dist/assets/{pt-BR-Ditt0LyE.js → pt-BR-CxNevoP6.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-8qBvK9Ph.js → renderElectronMiniChatApp-DUJVSIIx.js} +2 -2
- package/dist/assets/{renderMobileApp-DlzbiKPe.js → renderMobileApp-_gDjCUfy.js} +4 -4
- package/dist/assets/{runtimeConfig-CiXYAKZA.js → runtimeConfig-B2oF54M_.js} +1 -1
- package/dist/assets/{runtimeEndpointReset-CJ75UJCg.js → runtimeEndpointReset-B-K7EVqE.js} +2 -2
- package/dist/assets/{scheduledTaskNavigation-Cnm1DAZg.js → scheduledTaskNavigation-HqH8WVi0.js} +1 -1
- package/dist/assets/{sessionChangeSummary-Cj9hELGP.js → sessionChangeSummary-gZxQHRZk.js} +1 -1
- package/dist/assets/{sessionLookup-DNBHHgWV.js → sessionLookup-IdZulsfX.js} +1 -1
- package/dist/assets/{sortable-tabs-strip-DwjmBdDS.js → sortable-tabs-strip-iF-Lsdrw.js} +1 -1
- package/dist/assets/{speechSettingsQueries-DmpOjA8z.js → speechSettingsQueries-DRoGbuDe.js} +1 -1
- package/dist/assets/src-OU8Px6Wu.css +2 -0
- package/dist/assets/{store-D6XK1qew.js → store-CKdJiGxW.js} +3 -3
- package/dist/assets/{textarea-Ci46Ymdc.js → textarea-COrQqu0T.js} +1 -1
- package/dist/assets/{tooltip-BfZgnZ6x.js → tooltip-GgfMkvSY.js} +1 -1
- package/dist/assets/{types-CNeUb9mY.js → types-DXru0kiy.js} +1 -1
- package/dist/assets/{uk-DFoTnIxi.js → uk-B4NY4iyI.js} +1 -1
- package/dist/assets/{useAppFontEffects-DwoSkAza.js → useAppFontEffects-DgsSPrpH.js} +8 -8
- package/dist/assets/{useDesktopWindowControlsLayout-CjdGePjj.js → useDesktopWindowControlsLayout-wmICpJAQ.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-DwavBbA1.js → useEffectiveDirectory-dE7LTjY9.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-B5JVNRZO.js → useMobileNavigationStore-BOl-8KLV.js} +6 -6
- package/dist/assets/{useWorkerHighlightedLines-CKjw_rwT.js → useWorkerHighlightedLines-CjQu2mXA.js} +1 -1
- package/dist/assets/{zh-CN-Cw2OYvFl.js → zh-CN-CHBpOEbP.js} +1 -1
- package/dist/assets/{zh-TW-CPuXOw_f.js → zh-TW-DTVob60i.js} +1 -1
- package/dist/index.html +6 -6
- package/dist/mini-chat.html +6 -6
- package/dist/mobile.html +6 -6
- package/package.json +1 -1
- package/server/lib/assistants/DOCUMENTATION.md +2 -0
- package/server/lib/assistants/harness.js +4 -4
- package/server/lib/assistants/harness.test.js +9 -3
- package/dist/assets/MobileShareBridge-DNXTEHDF.js +0 -4
- package/dist/assets/src-j6H_WgaE.css +0 -2
package/dist/index.html
CHANGED
|
@@ -560,7 +560,7 @@
|
|
|
560
560
|
opacity: 0.72;
|
|
561
561
|
}
|
|
562
562
|
</style>
|
|
563
|
-
<script type="module" crossorigin src="/assets/main-
|
|
563
|
+
<script type="module" crossorigin src="/assets/main-BlhgRbh6.js"></script>
|
|
564
564
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js">
|
|
565
565
|
<link rel="modulepreload" crossorigin href="/assets/runtime-auth-ef9W7A43.js">
|
|
566
566
|
<link rel="modulepreload" crossorigin href="/assets/runtime-switch-CAZiOV2G.js">
|
|
@@ -583,11 +583,11 @@
|
|
|
583
583
|
<link rel="modulepreload" crossorigin href="/assets/platform-7bX6qtBV.js">
|
|
584
584
|
<link rel="modulepreload" crossorigin href="/assets/terminalApi-BHXvha-U.js">
|
|
585
585
|
<link rel="modulepreload" crossorigin href="/assets/runtime-file-download-DAOam_oV.js">
|
|
586
|
-
<link rel="modulepreload" crossorigin href="/assets/types-
|
|
587
|
-
<link rel="modulepreload" crossorigin href="/assets/capgoAdapter-
|
|
588
|
-
<link rel="modulepreload" crossorigin href="/assets/native-config-
|
|
589
|
-
<link rel="modulepreload" crossorigin href="/assets/runtimeConfig-
|
|
590
|
-
<link rel="stylesheet" crossorigin href="/assets/src-
|
|
586
|
+
<link rel="modulepreload" crossorigin href="/assets/types-DXru0kiy.js">
|
|
587
|
+
<link rel="modulepreload" crossorigin href="/assets/capgoAdapter-C8LWpfj0.js">
|
|
588
|
+
<link rel="modulepreload" crossorigin href="/assets/native-config-DAksnjPm.js">
|
|
589
|
+
<link rel="modulepreload" crossorigin href="/assets/runtimeConfig-B2oF54M_.js">
|
|
590
|
+
<link rel="stylesheet" crossorigin href="/assets/src-OU8Px6Wu.css">
|
|
591
591
|
</head>
|
|
592
592
|
<body class="h-full bg-background text-foreground">
|
|
593
593
|
<!-- Keep the startup layer outside #root. React replaces every child of
|
package/dist/mini-chat.html
CHANGED
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
}
|
|
75
75
|
</style>
|
|
76
76
|
|
|
77
|
-
<script type="module" crossorigin src="/assets/miniChat-
|
|
77
|
+
<script type="module" crossorigin src="/assets/miniChat-NFM4xI9m.js"></script>
|
|
78
78
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js">
|
|
79
79
|
<link rel="modulepreload" crossorigin href="/assets/runtime-auth-ef9W7A43.js">
|
|
80
80
|
<link rel="modulepreload" crossorigin href="/assets/runtime-switch-CAZiOV2G.js">
|
|
@@ -97,11 +97,11 @@
|
|
|
97
97
|
<link rel="modulepreload" crossorigin href="/assets/platform-7bX6qtBV.js">
|
|
98
98
|
<link rel="modulepreload" crossorigin href="/assets/terminalApi-BHXvha-U.js">
|
|
99
99
|
<link rel="modulepreload" crossorigin href="/assets/runtime-file-download-DAOam_oV.js">
|
|
100
|
-
<link rel="modulepreload" crossorigin href="/assets/types-
|
|
101
|
-
<link rel="modulepreload" crossorigin href="/assets/capgoAdapter-
|
|
102
|
-
<link rel="modulepreload" crossorigin href="/assets/native-config-
|
|
103
|
-
<link rel="modulepreload" crossorigin href="/assets/runtimeConfig-
|
|
104
|
-
<link rel="stylesheet" crossorigin href="/assets/src-
|
|
100
|
+
<link rel="modulepreload" crossorigin href="/assets/types-DXru0kiy.js">
|
|
101
|
+
<link rel="modulepreload" crossorigin href="/assets/capgoAdapter-C8LWpfj0.js">
|
|
102
|
+
<link rel="modulepreload" crossorigin href="/assets/native-config-DAksnjPm.js">
|
|
103
|
+
<link rel="modulepreload" crossorigin href="/assets/runtimeConfig-B2oF54M_.js">
|
|
104
|
+
<link rel="stylesheet" crossorigin href="/assets/src-OU8Px6Wu.css">
|
|
105
105
|
</head>
|
|
106
106
|
<body class="h-full bg-background text-foreground">
|
|
107
107
|
<div id="root" class="h-full">
|
package/dist/mobile.html
CHANGED
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
})();
|
|
64
64
|
</script>
|
|
65
65
|
|
|
66
|
-
<script type="module" crossorigin src="/assets/mobile-
|
|
66
|
+
<script type="module" crossorigin src="/assets/mobile-DRtQrc9q.js"></script>
|
|
67
67
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js">
|
|
68
68
|
<link rel="modulepreload" crossorigin href="/assets/runtime-auth-ef9W7A43.js">
|
|
69
69
|
<link rel="modulepreload" crossorigin href="/assets/runtime-switch-CAZiOV2G.js">
|
|
@@ -86,11 +86,11 @@
|
|
|
86
86
|
<link rel="modulepreload" crossorigin href="/assets/platform-7bX6qtBV.js">
|
|
87
87
|
<link rel="modulepreload" crossorigin href="/assets/terminalApi-BHXvha-U.js">
|
|
88
88
|
<link rel="modulepreload" crossorigin href="/assets/runtime-file-download-DAOam_oV.js">
|
|
89
|
-
<link rel="modulepreload" crossorigin href="/assets/types-
|
|
90
|
-
<link rel="modulepreload" crossorigin href="/assets/capgoAdapter-
|
|
91
|
-
<link rel="modulepreload" crossorigin href="/assets/native-config-
|
|
92
|
-
<link rel="modulepreload" crossorigin href="/assets/runtimeConfig-
|
|
93
|
-
<link rel="stylesheet" crossorigin href="/assets/src-
|
|
89
|
+
<link rel="modulepreload" crossorigin href="/assets/types-DXru0kiy.js">
|
|
90
|
+
<link rel="modulepreload" crossorigin href="/assets/capgoAdapter-C8LWpfj0.js">
|
|
91
|
+
<link rel="modulepreload" crossorigin href="/assets/native-config-DAksnjPm.js">
|
|
92
|
+
<link rel="modulepreload" crossorigin href="/assets/runtimeConfig-B2oF54M_.js">
|
|
93
|
+
<link rel="stylesheet" crossorigin href="/assets/src-OU8Px6Wu.css">
|
|
94
94
|
</head>
|
|
95
95
|
<body class="h-full bg-background text-foreground">
|
|
96
96
|
<div id="root" class="h-full"></div>
|
package/package.json
CHANGED
|
@@ -223,6 +223,8 @@ and keep their existing error result handling.
|
|
|
223
223
|
|
|
224
224
|
**Create assistant / schedule task (this PR)**
|
|
225
225
|
|
|
226
|
+
Reply language follows the user's latest substantive message and conversation context, with explicit language requests taking precedence. Ambiguous messages and background follow-ups retain the conversation language. The built-in prompt and terminal-tool summary never select a response language from UI locale. Reset summaries receive the current user request as language context alongside the reset result, without restoring earlier history. Explicit `{{LANGUAGE}}` placeholders in user-authored `defaultPrompt` retain their locale substitution contract; the built-in prompt no longer uses that token.
|
|
227
|
+
|
|
226
228
|
- `create_assistant` calls the same in-process `createAssistant` (`name`, connected OpenCode `providerID`/`modelID`, `mode: 'continuous'`). It emits an `assistant` card that opens that contact.
|
|
227
229
|
- `schedule_task` calls in-process `projectConfigRuntime.upsertScheduledTask` with the same payload as `PUT /api/projects/:id/scheduled-tasks` (`name`, `schedule.kind/time/timezone`, `execution.prompt` + provider/model) on a registered project, then best-effort `scheduledTasksRuntime.syncProject`. It emits a `schedule` card.
|
|
228
230
|
- Successful `schedule_task` also writes an assistants-owned mapping row in `assistants.sqlite` (`assistant_scheduled_task`: assistantID + projectID + taskID). Project-config execution strips unknown fields, so ownership stays out of the task payload. `GET /api/yuri/assistants/:id/scheduled-tasks` returns those mappings joined with live `listScheduledTasks` records when possible; failed project lookups keep the mapping with `task: null`.
|
|
@@ -102,8 +102,8 @@ export const CONTACT_SYSTEM_PROMPT = [
|
|
|
102
102
|
'Handle simple questions, file lookups, and small, clearly scoped configuration changes directly when their scope and verification are straightforward. As a task grows into implementation, multi-step debugging, or broad changes, hand it to a worker session. An explicit user request to handle a bounded task yourself can use the direct tools.',
|
|
103
103
|
'Reply in short chat bubbles: a few sentences each, separated by a blank line.',
|
|
104
104
|
'Talk like a person in the user\'s language. One short spoken bubble at a time — never a wall of paragraphs.',
|
|
105
|
-
'
|
|
106
|
-
'Keep private reasoning and tool traces private. Communicate your next concrete action, verified milestones, and blockers in short natural messages in
|
|
105
|
+
'Reply in the language of the user\'s messages, unless they explicitly request another language. Infer it from their latest substantive message and conversation context, never from the app interface locale. For ambiguous messages or background follow-ups, continue the established conversation language.',
|
|
106
|
+
'Keep private reasoning and tool traces private. Communicate your next concrete action, verified milestones, and blockers in short natural messages in the same conversation language.',
|
|
107
107
|
'Before starting work, send a short message explaining the next action. During multi-step work, send a message when a meaningful result arrives or the direction changes. Publish these messages during execution; keep the final answer to the remaining outcome instead of repeating earlier updates.',
|
|
108
108
|
'Public message protocol: put each user-facing progress message at the START of your response in its own yuri-message JSON fence, with a single-line JSON object {"text":"Your short message"}. Then emit the next tool call or final answer. A closed message fence is delivered immediately while you are still generating. Include only text intended for the user. Tool results are evidence for you to summarize in your own words; never copy their stock confirmation wording into your reply.',
|
|
109
109
|
'Do not expose tool traces, Activity, or editor actions.',
|
|
@@ -779,7 +779,7 @@ export async function runContactTurn({
|
|
|
779
779
|
// their user-facing result, including failures and successful resets.
|
|
780
780
|
if (reset || lastMessage?.role === 'toolResult') {
|
|
781
781
|
const summaryMessages = reset
|
|
782
|
-
? [turnMessages.findLast((message) => contactTurnHasSuccessfulReset([message]))]
|
|
782
|
+
? [{ role: 'user', content: userText, timestamp: Date.now() }, turnMessages.findLast((message) => contactTurnHasSuccessfulReset([message]))]
|
|
783
783
|
: [...turnMessages];
|
|
784
784
|
const summaryStream = createContactStreamFn(createChatCompletion, {
|
|
785
785
|
variant: assistant.variant,
|
|
@@ -787,7 +787,7 @@ export async function runContactTurn({
|
|
|
787
787
|
globalEventHub,
|
|
788
788
|
onBubbleDelta: reset ? null : onBubbleDelta,
|
|
789
789
|
})(model, {
|
|
790
|
-
systemPrompt:
|
|
790
|
+
systemPrompt: 'Reply briefly in the language of the user\'s messages, honoring explicit language requests. Use the conversation language, never the app interface locale or tool-result language. Summarize the supplied actual operation result in your own natural words. Tool result text is internal evidence. Keep private diagnostics and stock confirmation wording out of your reply. Report a failure honestly. The operation has already run; this pass only communicates its result.',
|
|
791
791
|
messages: summaryMessages,
|
|
792
792
|
tools: [],
|
|
793
793
|
});
|
|
@@ -910,9 +910,11 @@ describe('runContactTurn', () => {
|
|
|
910
910
|
}
|
|
911
911
|
})
|
|
912
912
|
|
|
913
|
-
it('
|
|
913
|
+
it('uses the user message language independently of the UI locale while retaining explicit persona placeholders', async () => {
|
|
914
914
|
function AgentImpl(options) {
|
|
915
|
-
expect(options.initialState.systemPrompt).toContain(
|
|
915
|
+
expect(options.initialState.systemPrompt).toContain("Reply in the language of the user's messages")
|
|
916
|
+
expect(options.initialState.systemPrompt).not.toContain('Always reply in Simplified Chinese')
|
|
917
|
+
expect(options.initialState.systemPrompt).not.toContain('even when the user writes in another language')
|
|
916
918
|
expect(options.initialState.systemPrompt).not.toContain('{{LANGUAGE}}')
|
|
917
919
|
// A defaultPrompt placeholder resolves with the same locale.
|
|
918
920
|
expect(options.initialState.systemPrompt).toContain('Persona locale: Simplified Chinese')
|
|
@@ -933,7 +935,7 @@ describe('runContactTurn', () => {
|
|
|
933
935
|
it('falls back to a neutral phrase for unknown or missing locale without leaking the token', async () => {
|
|
934
936
|
function AgentImpl(options) {
|
|
935
937
|
expect(options.initialState.systemPrompt).not.toContain('{{LANGUAGE}}')
|
|
936
|
-
expect(options.initialState.systemPrompt).toContain("
|
|
938
|
+
expect(options.initialState.systemPrompt).toContain("Reply in the language of the user's messages")
|
|
937
939
|
this.state = { ...options.initialState, messages: [{ role: 'assistant', content: [{ type: 'text', text: 'ok' }] }] }
|
|
938
940
|
this.prompt = async () => {}
|
|
939
941
|
}
|
|
@@ -1456,6 +1458,9 @@ describe('runContactTurn', () => {
|
|
|
1456
1458
|
completions += 1
|
|
1457
1459
|
if (completions === 2) {
|
|
1458
1460
|
expect(JSON.stringify(body)).not.toContain('secret')
|
|
1461
|
+
expect(body.messages[0].content).toContain("language of the user's messages")
|
|
1462
|
+
expect(body.messages[0].content).not.toContain('Reply briefly in English')
|
|
1463
|
+
expect(body.messages.some((message) => message.role === 'user' && message.content === '清空聊天记录')).toBe(true)
|
|
1459
1464
|
return { text: '聊天记录已清空。' }
|
|
1460
1465
|
}
|
|
1461
1466
|
if (completions > 4) {
|
|
@@ -1479,6 +1484,7 @@ describe('runContactTurn', () => {
|
|
|
1479
1484
|
{ role: 'assistant', content: 'remembered secret' },
|
|
1480
1485
|
],
|
|
1481
1486
|
userText: '清空聊天记录',
|
|
1487
|
+
language: 'en',
|
|
1482
1488
|
tools,
|
|
1483
1489
|
createChatCompletion,
|
|
1484
1490
|
// Default real Agent — only completion is stubbed (same pattern as assign terminate).
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-aparajita-capacitor-secure-storage-xol_6BsB.js","assets/rolldown-runtime-hePW80VL.js","assets/assistant-attachment-cache-CLnqffXU.js","assets/runtime-auth-ef9W7A43.js","assets/runtime-switch-CAZiOV2G.js","assets/queryRuntime-DKGLQtb9.js","assets/vendor-tanstack-query-core-BWz0ose6.js","assets/runtime-file-resource-C1k5nbWb.js","assets/vendor-base-ui-CdzJ6My_.js","assets/brand-storage-migration-Bhz6UOBJ.js","assets/vendor-react-BP2cRVqX.js","assets/vendor-tanstack-react-query-CdqCAt40.js","assets/useAssistantUIStore-D7JZlg_Q.js","assets/vendor-zustand-o69pgTEK.js","assets/useUIStore-NMQx_cnG.js","assets/brand-storage-bootstrap-D4BW3w-M.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{n as e,r as t}from"./rolldown-runtime-hePW80VL.js";import{E as n,b as r,w as i}from"./runtime-auth-ef9W7A43.js";import{c as a,i as o,l as s,n as c,r as l,t as u}from"./runtime-switch-CAZiOV2G.js";import{u as d}from"./queryRuntime-DKGLQtb9.js";import{St as f,jt as p,rt as m,tt as h,xt as g}from"./persistence-Dzooc9Xg.js";import{it as _,rt as v}from"./vendor-base-ui-CdzJ6My_.js";import{n as y,r as b}from"./platform-7bX6qtBV.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{n as ee}from"./vendor-react-BP2cRVqX.js";import{a as x}from"./runtime-file-resource-C1k5nbWb.js";import{a as te,n as S,o as C,t as ne}from"./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js";import{n as w}from"./vendor-reactuses-core-BpfIZ1tg.js";import{f as re}from"./button-CcMfow51.js";import{N as ie,c as T,l as E,m as ae,s as oe,t as se,w as ce}from"./MobileDetailNavigation-BkqkecBf.js";import{bo as D,o as le}from"./useMobileNavigationStore-B5JVNRZO.js";import{i as O,n as ue}from"./useAssistantUIStore-D7JZlg_Q.js";import{r as de,t as fe}from"./AgentAvatar-BsXXkno4.js";import{n as pe}from"./Icon-CZFN8X-2.js";import{n as me,t as he}from"./dialog-CCD3bivZ.js";import{t as ge}from"./rasterizePng-056Poix7.js";var _e=ee(),k=t(_(),1),ve=`yuri.mobile.connections.v1`,ye=`yuri.mobile.`,be=`yuri.mobile.deviceId`,xe=()=>{try{let e=window.localStorage.getItem(be);if(e&&e.trim())return e.trim();let t=h();return window.localStorage.setItem(be,t),t}catch{return h()}},Se=()=>`mobile:${xe()}`,Ce=()=>{try{let e=S.getPlatform();return e===`ios`||e===`android`?e:void 0}catch{return}},we=12,Te=8e3,Ee=2500,De=3e3,Oe=2500,A=e=>{let t=e.trim();if(!t)return``;let n=/^https?:\/\//i.test(t)?t:`http://${t}`,r=new URL(n);return r.hash=``,r.search=``,r.pathname=r.pathname.replace(/\/+$/,``),r.toString().replace(/\/+$/,``)},ke=e=>{try{return new URL(e).host}catch{return e}},j=e=>{try{return A(e)}catch{return e.trim().replace(/\/+$/g,``)}},Ae=(e,t)=>j(e)===j(t),je=e=>`relay:${e.serverId}@${e.relayUrl.trim()}`,Me=e=>`relay://${e.serverId}`,Ne=e=>e.candidates.filter(e=>e.kind===`direct`),M=e=>{let t=e.candidates.find(e=>e.kind===`relay`);return t&&t.kind===`relay`?t.relay:null},N=e=>{let t=Ne(e)[0];if(t)return t.url;let n=M(e);return n?Me(n):``},P=e=>{let t=M(e);if(t)return je(t);let n=Ne(e)[0];return n?j(n.url):``},Pe=P,Fe=(e,t)=>{let n=e.find(e=>e.kind===`relay`),r=n&&n.kind===`relay`?n.relay.serverId:null,i=n&&n.kind===`relay`?n.relay.relayUrl.trim():null,a=new Set(e.filter(e=>e.kind===`direct`).map(e=>j(e.url)));return t.some(e=>e.kind===`relay`?r!==null&&e.relay.serverId===r&&e.relay.relayUrl.trim()===i:a.has(j(e.url)))},Ie=(e,t)=>t.id&&e.id===t.id?!0:Fe(e.candidates,t.candidates),Le=e=>{let t=(()=>{try{return A(e)}catch{return``}})();return t?[{kind:`direct`,url:t}]:[]},Re=e=>{if(e.candidates&&e.candidates.length>0)return e.candidates;let t=[];return typeof e.url==`string`&&e.url.trim()&&!/^relay:\/\//i.test(e.url.trim())&&t.push(...Le(e.url)),e.relay&&t.push({kind:`relay`,relay:e.relay}),t},ze=e=>{if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e;if(typeof t.relayUrl!=`string`||!t.relayUrl.trim()||typeof t.serverId!=`string`||!t.serverId.trim())return null;let n=t.hostEncPubJwk;if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=n;return r.kty!==`EC`||r.crv!==`P-256`||typeof r.x!=`string`||!r.x||typeof r.y!=`string`||!r.y?null:{relayUrl:t.relayUrl,serverId:t.serverId,hostEncPubJwk:{kty:`EC`,crv:`P-256`,x:r.x,y:r.y}}},Be=e=>{try{return JSON.stringify(e)}catch{return String(e)}},F=(e,t={})=>{Be(t)},I=(e,t={})=>{Be(t)},Ve=e=>{if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch{return e}},He=e=>{if(typeof e!=`string`)return e??void 0;try{return JSON.parse(e)}catch{return e}},Ue=async(e,t)=>{if(!y())return null;try{let{CapacitorHttp:n}=await C(async()=>{let{CapacitorHttp:e}=await import(`./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js`).then(e=>e.i);return{CapacitorHttp:e}},__vite__mapDeps([0,1])),r=Object.fromEntries(new Headers(t?.headers).entries()),i=await n.request({url:e,method:t?.method||`GET`,headers:r,data:He(t?.body)});return{ok:i.status>=200&&i.status<300,status:i.status,source:`native-http`,json:async()=>Ve(i.data)}}catch(t){return console.warn(`[mobile-connect]`,`native-http failed`,Be({url:e,error:t instanceof Error?t.message:String(t)})),null}},We=async(e,t)=>{let n=await fetch(e,t).catch(t=>(console.warn(`[mobile-connect]`,`browser-fetch failed`,Be({url:e,error:t instanceof Error?t.message:String(t)})),null));return n?{ok:n.ok,status:n.status,source:`browser-fetch`,json:()=>n.json()}:null},L=async(e,t,n)=>{let r,i=new Promise(t=>{r=window.setTimeout(()=>{n?.(),t(null)},e)});try{return await Promise.race([t,i])}catch{return null}finally{r!==void 0&&window.clearTimeout(r)}},R=async(e,t,n)=>{let r=n?.totalTimeoutMs??Te,i=Date.now(),a=await L(Math.min(Ee,r),Ue(e,t));if(a)return a;let o=new AbortController;return L(Math.max(500,r-(Date.now()-i)),We(e,{...t,signal:o.signal}),()=>o.abort())},Ge=async e=>{if(!e)return null;let t=await e.json().catch(()=>null);if(!t||typeof t!=`object`)return null;let n=t;return{authenticated:typeof n.authenticated==`boolean`?n.authenticated:void 0,disabled:typeof n.disabled==`boolean`?n.disabled:void 0,scope:typeof n.scope==`string`?n.scope:void 0}},z=15e3,Ke=async(e,t,r,i=z,a)=>{let o=n({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk,...r?{grant:r}:{}}),s=e=>e===`ok`&&a?.keepTunnel?{outcome:e,tunnel:o}:(o.close(),{outcome:e});try{let e=t?{Authorization:`Bearer ${t}`}:void 0,n=await L(i,o.fetch(`/auth/session`,{headers:e}).catch(()=>null));if(F(`relay:session`,{ok:n?.ok===!0,status:n?.status??null,hasToken:!!t}),!n)return s(`unreachable`);if(n.status===401)return s(t?`auth-failed`:`needs-login`);if(!n.ok&&n.status!==404)return s(`auth-failed`);let r=await Ge(n);return r&&r.disabled!==!0&&r.authenticated===!1?s(t?`auth-failed`:`needs-login`):s(`ok`)}catch(e){throw o.close(),e}},qe=(e,t,n,i,a)=>{let o=typeof window<`u`?window.location.origin:``,c={relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk,...n?{grant:n}:{}};a&&r(c,a),s({apiBaseUrl:o,clientToken:t,runtimeKey:i??je(e),relay:c})},Je=e=>{if(!e||typeof e!=`object`)return null;let t=e;if(t.kind===`direct`)return typeof t.url==`string`&&t.url.trim()?{kind:`direct`,url:t.url}:null;if(t.kind===`relay`){let e=ze(t.relay);return e?{kind:`relay`,relay:e}:null}return null},Ye=e=>{if(e.mode===`relay`){let t=ze(e.relay);return t?[{kind:`relay`,relay:t}]:[]}return typeof e.url==`string`?Le(e.url):[]},B=()=>{if(typeof window>`u`)return[];let e;try{e=JSON.parse(window.localStorage.getItem(ve)||`[]`)}catch{return[]}if(!Array.isArray(e))return[];let t=y();return e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let n=e;if(typeof n.id!=`string`)return[];let r=Array.isArray(n.candidates)?n.candidates.map(Je).filter(e=>!!e):Ye(n);if(r.length===0)return[];let i=typeof n.clientToken==`string`&&n.clientToken.trim()?n.clientToken:void 0,a=typeof n.label==`string`&&n.label.trim()?n.label:ke(N({candidates:r})),o={id:n.id,label:a,candidates:r,lastUsedAt:typeof n.lastUsedAt==`number`?n.lastUsedAt:0};return t?[{...o,hasToken:!!n.hasToken||!!i}]:[{...o,clientToken:i,hasToken:!!i}]}).sort((e,t)=>t.lastUsedAt-e.lastUsedAt)},Xe=e=>e.kind===`relay`?{kind:`relay`,relay:{relayUrl:e.relay.relayUrl,serverId:e.relay.serverId,hostEncPubJwk:e.relay.hostEncPubJwk}}:{kind:`direct`,url:e.url},V=e=>{if(typeof window>`u`)return;let t=y(),n=e.slice(0,we).map(e=>{let n={id:e.id,label:e.label,candidates:e.candidates.map(Xe),lastUsedAt:e.lastUsedAt};return t?{...n,hasToken:!!(e.hasToken||e.clientToken)}:{...n,clientToken:e.clientToken}});try{window.localStorage.setItem(ve,JSON.stringify(n))}catch(e){throw console.warn(`[mobile-storage] failed to persist connection metadata`,e),e}},Ze=(e,t,n=!0)=>{let r=e.find(e=>Ie(e,t)),i=y(),a={id:t.id||r?.id||h(),label:t.label,candidates:t.candidates,lastUsedAt:n?Date.now():r?.lastUsedAt??0,...i?{hasToken:t.hasToken??(!!t.clientToken||r?.hasToken||!1)}:{clientToken:t.clientToken??r?.clientToken,hasToken:!!(t.clientToken??r?.clientToken)}};return[a,...e.filter(e=>e.id!==a.id&&!Ie(e,t))].sort((e,t)=>t.lastUsedAt-e.lastUsedAt).slice(0,we)},Qe=ne,$e=0,et=e=>`${ye}token.${encodeURIComponent(e)}`,tt=async(e,t)=>{let n,r=new Promise(e=>{n=window.setTimeout(()=>e(t),De)});try{return await Promise.race([e.catch(()=>t),r])}finally{n!==void 0&&window.clearTimeout(n)}},nt=async(e,t,n)=>y()?tt(t().catch(t=>(console.warn(`[mobile-storage] ${e} failed`,t),n)),n):n,H=async e=>{I(`secure:read-start`,{key:e});let t=await nt(`secure:read`,async()=>(await Qe.internalGetItem({prefixedKey:et(e),sync:!1})).data,null),n=typeof t==`string`&&t.trim()?t:void 0;return I(`secure:read`,{key:e,hasToken:!!n}),n},U=async(e,t)=>{I(`secure:write-start`,{key:e});let n=await nt(`secure:write`,async()=>(await Qe.internalSetItem({prefixedKey:et(e),data:t,sync:!1,access:$e}),!0),!1);return I(`secure:write`,{key:e,ok:n}),n},rt=async e=>{await nt(`secure:delete`,async()=>(await Qe.internalRemoveItem({prefixedKey:et(e),sync:!1}),!0),!1)},it=async()=>{if(typeof window>`u`||!y())return;let e;try{e=JSON.parse(window.localStorage.getItem(ve)||`[]`)}catch{return}if(!Array.isArray(e))return;let t=e.filter(e=>!!e&&typeof e==`object`&&typeof e.url==`string`&&typeof e.clientToken==`string`&&!!e.clientToken.trim());if(t.length!==0){I(`secure:migrate-start`,{count:t.length});for(let{url:e,clientToken:n}of t)await U(j(e),n);V(B()),I(`secure:migrate-done`,{count:t.length})}},at=async()=>(await it(),B()),ot=async e=>{let t=Ze(B(),e);if(V(t),y()&&e.clientToken){let n=t[0];n&&await U(P(n),e.clientToken)}return t},st=async e=>{let t=B(),n=t.find(t=>t.id===e)??null,r=t.filter(t=>t.id!==e);if(n){let e;if(y())try{e=await H(P(n))||void 0}catch{e=void 0}else typeof n.clientToken==`string`&&n.clientToken.trim()&&(e=n.clientToken.trim());if(e)try{let{clearAssistantAttachmentCacheForBearer:t}=await C(async()=>{let{clearAssistantAttachmentCacheForBearer:e}=await import(`./assistant-attachment-cache-CLnqffXU.js`).then(e=>e.t);return{clearAssistantAttachmentCacheForBearer:e}},__vite__mapDeps([2,1,3,4,5,6,7,8,9,10,11,0]));await t(e,`forget-connection`)}catch{}}if(V(r),n&&y()&&await rt(P(n)),n){let e=P(n);try{let{useAssistantUIStore:t}=await C(async()=>{let{useAssistantUIStore:e}=await import(`./useAssistantUIStore-D7JZlg_Q.js`).then(e=>e.a);return{useAssistantUIStore:e}},__vite__mapDeps([12,1,4,3,13,8,14,15,9]));t.getState().removeCatalogPartition(e);let{publishNativeAssistantCatalog:n}=await C(async()=>{let{publishNativeAssistantCatalog:e}=await Promise.resolve().then(()=>en);return{publishNativeAssistantCatalog:e}},void 0);await n().catch(()=>void 0)}catch{console.warn(`[mobile-storage] connection catalog cleanup failed`)}}return r},ct=1500,W=async(e,t,n)=>{let r=n?.fast?{totalTimeoutMs:Oe}:void 0,i=M({candidates:e})?.serverId??null,a=e.find(e=>e.kind===`relay`)??null,o=e.filter(e=>e.kind===`direct`),s=async()=>{for(let e of o){let n=A(e.url)||e.url,a=t?{Authorization:`Bearer ${t}`}:void 0,o=await R(`${n}/health`,{method:`GET`},r);if(!o?.ok)continue;if(i){let e=await o.json().catch(()=>null),t=e&&typeof e==`object`?e.serverId:null;if(typeof t==`string`&&t&&t!==i){F(`probe:server-id-mismatch`,{url:n});continue}}let s=await R(`${n}/auth/session`,{method:`GET`,credentials:`include`,headers:a},r);if(s?.status===401)return{status:`needs-login`};if(!s||!s.ok&&s.status!==404)continue;let c=await Ge(s);if(c&&c.disabled!==!0&&c.authenticated===!1)return{status:`needs-login`};let l=c?.disabled===!0;return!t&&y()&&!l&&c?.scope!==`client`?{status:`needs-login`}:{status:`ok`,transport:{kind:`direct`,url:n}}}return{status:`unreachable`}},c=async()=>{if(!a)return{status:`unreachable`};let{outcome:e,tunnel:r}=await Ke(a.relay,t,void 0,n?.fast?Oe:void 0,{keepTunnel:!0});return e===`ok`?{status:`ok`,transport:{kind:`relay`,relay:a.relay,tunnel:r}}:e===`needs-login`||e===`auth-failed`?{status:`needs-login`}:{status:`unreachable`}};return a?o.length===0?c():new Promise(e=>{let t=!1,n=!1,r,i=null,a=null,o=e=>{e?.status===`ok`&&e.transport.kind===`relay`&&e.transport.tunnel?.close()},l=n=>{t||(t=!0,e(n))},u=()=>{n||t||(r!==void 0&&(window.clearTimeout(r),r=void 0),c().then(e=>{if(a=e,t||n){o(e);return}if(e.status===`ok`||e.status===`needs-login`){l(e);return}i&&l(i)}))};s().then(e=>{if(i=e,!t){if(e.status===`ok`||e.status===`needs-login`){n=!0,r!==void 0&&window.clearTimeout(r),o(a),l(e);return}if(a){l(a);return}u()}}),r=window.setTimeout(u,ct)}):s()},G=(e,t,n)=>{e.kind===`relay`?qe(e.relay,t,n?.grant,n?.runtimeKey,e.tunnel):s({apiBaseUrl:e.url,clientToken:t,runtimeKey:n?.runtimeKey}),Ct()},lt=()=>{let e=B()[0];return e?.label?.trim()?e.label:null},ut=async()=>{await it();let e=B()[0];if(!e)return!1;let t;if(y()){if(!e.hasToken||(t=await H(P(e)),!t))return!1}else if(t=e.clientToken,!t)return!1;let n=await W(e.candidates,t);return n.status===`ok`&&(await ot({id:e.id,label:e.label,candidates:e.candidates}),G(n.transport,t,{runtimeKey:P(e)}),!0)},dt=async(e,t)=>{let n=(await at()).find(t=>P(t)===e);if(!n)return`missing`;let r=y()?n.hasToken?await H(e):void 0:n.clientToken;if(!r)return`auth-required`;let i=t?.transportPreference===`relay`?n.candidates.filter(e=>e.kind===`relay`):n.candidates;if(i.length===0)return`offline`;let a=await W(i,r,{fast:!0});return a.status===`needs-login`?`auth-required`:a.status===`ok`?(G(a.transport,r,{runtimeKey:e}),`connected`):`offline`},ft=async(e,t)=>{let n=``;try{n=A(e.url)}catch{return!1}if(!n)return!1;let r=e.clientToken?.trim()||void 0,i=r?{Authorization:`Bearer ${r}`}:void 0,a=t?.fast?{totalTimeoutMs:Oe}:void 0;if(!(await R(`${n}/health`,{method:`GET`,headers:i},a))?.ok)return!1;let o=await R(`${n}/auth/session`,{method:`GET`,credentials:`include`,headers:i},a);if(!o||!o.ok&&o.status!==404)return!1;let s=await Ge(o);return!(s&&s.disabled!==!0&&s.authenticated===!1)},pt=e=>[...e].sort((e,t)=>{let n=(e.priority??100)-(t.priority??100);if(n!==0)return n;let r=e=>e.type===`relay`?2:+!e.url.startsWith(`https://`);return r(e)-r(t)}).flatMap(e=>{if(e.type===`relay`){let t=ze({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk});return t?[{kind:`relay`,relay:t}]:[]}return Le(e.url)}),mt=async e=>{let t=M({candidates:e})?.serverId??null;for(let r of e){if(r.kind===`relay`){let e=n(r.relay),t=await L(z,e.fetch(`/health`).catch(()=>null));if(F(`establish:relay:health`,{ok:t?.ok===!0,status:t?.status??null}),t?.ok)return{kind:`relay`,relay:r.relay,tunnel:e};e.close();continue}let e=A(r.url)||r.url,i=await R(`${e}/health`,{method:`GET`});if(F(`establish:direct:health`,{ok:i?.ok===!0,status:i?.status??null}),i?.ok){if(t){let n=await i.json().catch(()=>null),r=n&&typeof n==`object`?n.serverId:null;if(typeof r==`string`&&r&&r!==t){F(`establish:server-id-mismatch`,{url:e});continue}}return{kind:`direct`,url:e}}}return null},ht=async(e,t)=>{if(!i())return ft(e,t);let n=await L(t?.fast?Oe:z,d(`/auth/session`).then(e=>e).catch(()=>null));if(!n)return!0;if(n.status===401)return!1;if(!n.ok&&n.status!==404)return!0;let r=await Ge(n);return!(r&&r.disabled!==!0&&r.authenticated===!1)},gt=e=>e.kind===`relay`?i():!i()&&Ae(e.url,u()),_t=()=>{let e=l();return e?B().find(t=>P(t)===e)??null:null},vt=e=>{let t=l();return!!t&&P(e)===t},yt=async()=>{let e=_t();if(!e)return`no-connection`;let t;if(t=y()?e.hasToken?await H(P(e)):void 0:e.clientToken,!t)return`unreachable`;let n=e.candidates.findIndex(e=>gt(e.kind===`relay`?{kind:`relay`,relay:e.relay}:{kind:`direct`,url:e.url})),r=await W(n>=0?e.candidates.slice(0,n):e.candidates,t,{fast:!0});if(r.status===`ok`)return await ot({id:e.id,label:e.label,candidates:e.candidates}),G(r.transport,t,{runtimeKey:P(e)}),`switched`;if(r.status===`needs-login`)return`unreachable`;if(n>=0&&await ht({url:u(),clientToken:t},{fast:!0}))return Ct(),`unchanged`;let i=await W(n>=0?e.candidates.slice(n+1):[],t,{fast:!0});return i.status===`ok`?(await ot({id:e.id,label:e.label,candidates:e.candidates}),G(i.transport,t,{runtimeKey:P(e)}),`switched`):`unreachable`},bt=5e3,xt=!1,St=async()=>{if(xt)return`skipped`;let e=_t();if(!e)return F(`candidates:refresh-skip`,{reason:`no-active-connection`}),`skipped`;let t=M(e);if(!t)return F(`candidates:refresh-skip`,{reason:`no-relay-candidate`}),`skipped`;xt=!0;try{let n=await L(z,d(`/api/client-auth/connection/candidates`).then(e=>e).catch(()=>null));if(!n?.ok)return F(`candidates:refresh-skip`,{reason:`fetch-failed`,status:n?.status??null}),`skipped`;let r=await n.json().catch(()=>null);if(!r||r.serverId!==t.serverId)return F(`candidates:refresh-skip`,{reason:`server-id-mismatch`}),`skipped`;let i=Array.isArray(r.candidates)?r.candidates:[],a=[];for(let e of i){if(!e||typeof e!=`object`)continue;let t=e;if(t.type===`lan`&&typeof t.url==`string`)try{let e=A(t.url);e&&!a.includes(e)&&a.push(e)}catch{}}if(a.length===0)return F(`candidates:refresh-skip`,{reason:`no-lan-reported`}),`skipped`;let o=Ne(e).filter(e=>e.url.startsWith(`https://`)),s=[...a.map(e=>({kind:`direct`,url:e})),...o,{kind:`relay`,relay:t}];return JSON.stringify(e.candidates.map(Xe))===JSON.stringify(s.map(Xe))?`unchanged`:(F(`candidates:refreshed`,{lanCount:a.length}),await ot({id:e.id,label:e.label,candidates:s}),`updated`)}finally{xt=!1}},Ct=()=>{typeof window>`u`||window.setTimeout(()=>{(async()=>{let e=await St().catch(()=>`skipped`);F(`candidates:refresh-result`,{result:e}),e===`updated`&&i()&&await yt().catch(()=>null)})()},bt)},wt=e=>{let{t}=re(),[n,r]=k.useState(()=>B()),[i,a]=k.useState(null),[o,s]=k.useState(null),[c,l]=k.useState(null),u=k.useRef(n),d=k.useRef(0),f=k.useRef(null),p=k.useRef(new Set),m=w(()=>{e(),p.current.forEach(e=>e())}),g=w(e=>(p.current.add(e),()=>p.current.delete(e))),_=w(e=>{d.current+=1,u.current=e,r(e)}),v=w(e=>{f.current=e,a(e)}),b=w(e=>{f.current===e&&(f.current=null,a(null))}),ee=w(()=>s(t(`mobile.connect.history.updateFailed`)));k.useEffect(()=>{let e=!1,t=d.current;return at().then(n=>{!e&&d.current===t&&_(n)}).catch(()=>{e||ee()}),()=>{e=!0}},[_,ee]);let x=w((e,t=!0)=>{let n=Ze(u.current,e,t);return V(n),_(n),n}),te=w(async e=>{if(!f.current){s(null),v(`connect`);try{let n=Re(e);if(n.length===0){s(t(`mobile.connect.error.urlRequired`));return}let r=e.id?u.current.find(t=>t.id===e.id):u.current.find(e=>Fe(e.candidates,n)),i=e.label?.trim()||r?.label||ke(N({candidates:n})),a=e.relayGrant,o=e.clientToken?.trim()||void 0,c=!!o;o||(y()?r?.hasToken&&(o=await H(P(r))):o=r?.clientToken),F(`connect:start`,{candidates:n.map(e=>e.kind),hasToken:!!o});let d=await W(n,o);if(F(`connect:probe`,{status:d.status}),d.status===`unreachable`){s(t(`mobile.connect.error.unreachable`));return}if(d.status===`needs-login`){x({id:r?.id,label:i,candidates:n},!1),l({id:r?.id??h(),label:i,candidates:n,relay:M({candidates:n})??void 0,relayGrant:a});return}let f=P({candidates:n});o&&c&&y()&&await U(f,o),x({id:r?.id,label:i,candidates:n,clientToken:o}),G(d.transport,o??null,{runtimeKey:f,grant:a}),m()}catch(e){console.warn(`[mobile-connect] connect threw`,e),s(t(`mobile.connect.error.invalidUrl`))}finally{b(`connect`)}}}),S=w(async e=>{if(f.current)return;s(null),v(`pairing`);let n=pt(e.candidates),r=null,i=!1;try{if(r=await mt(n),!r){s(t(`mobile.connect.error.unreachable`));return}let a={method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({pairingId:e.pairingId,secret:e.secret,clientLabel:`Yuri Mobile`,clientKind:`mobile`,deviceName:`Yuri Mobile`,devicePlatform:Ce(),dedupeKey:Se()})},o=r.kind===`relay`?await L(z,r.tunnel.fetch(`/api/client-auth/pairing/redeem`,a).catch(()=>null)):await R(`${r.url}/api/client-auth/pairing/redeem`,a);if(!o?.ok){s(t(`mobile.connect.error.authRequired`));return}let c=await o.json().catch(()=>null),l=typeof c?.clientToken==`string`?c.clientToken.trim():``;if(!l){s(t(`mobile.connect.error.authRequired`));return}let u=typeof c?.server?.label==`string`?c.server.label:``,d=e.label||u||ke(N({candidates:n})),f=P({candidates:n});if(y()&&!await U(f,l)){s(t(`mobile.connect.error.authRequired`));return}x({label:d,candidates:n,clientToken:l}),G(r.kind===`relay`?{kind:`relay`,relay:r.relay,tunnel:r.tunnel}:{kind:`direct`,url:r.url},l,{runtimeKey:f}),i=r.kind===`relay`,m()}catch(e){console.warn(`[mobile-connect] pairing threw`,e),s(t(`mobile.connect.error.authRequired`))}finally{!i&&r?.kind===`relay`&&r.tunnel.close(),b(`pairing`)}}),C=w(async e=>{if(!c||!e.trim()||f.current)return;s(null),v(`password`);let{id:n,label:r,candidates:i}=c,a=null,o=!1;try{if(a=await mt(i),!a){s(t(`mobile.connect.error.unreachable`));return}let c={method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({password:e,trustDevice:!0,issueClientToken:!0,clientLabel:`Yuri Mobile`,clientKind:`mobile`,devicePlatform:Ce(),dedupeKey:Se()})};F(`password:start`,{transport:a.kind});let u=a.kind===`relay`?await L(z,a.tunnel.fetch(`/auth/session`,c).catch(()=>null)):await R(`${a.url}/auth/session`,c);if(F(`password:done`,{ok:u?.ok===!0,status:u?.status??null}),!u?.ok){s(t(`mobile.connect.error.passwordFailed`));return}let d=await u.json().catch(()=>null),f=typeof d?.clientToken==`string`?d.clientToken.trim():``;if(F(`password:token`,{issued:!!f}),!f){if(a.kind===`direct`&&!y()){x({id:n,label:r,candidates:i}),l(null),G({kind:`direct`,url:a.url},null,{runtimeKey:P({candidates:i})}),m();return}s(t(`mobile.connect.error.authRequired`));return}y()&&await U(P({candidates:i}),f),x({id:n,label:r,candidates:i,clientToken:f}),l(null),G(a.kind===`relay`?{kind:`relay`,relay:a.relay,tunnel:a.tunnel}:{kind:`direct`,url:a.url},f,{runtimeKey:P({candidates:i})}),o=a.kind===`relay`,m()}catch(e){console.warn(`[mobile-connect] password threw`,e),s(t(`mobile.connect.error.passwordFailed`))}finally{!o&&a?.kind===`relay`&&a.tunnel.close(),b(`password`)}}),ne=w(()=>{l(null),s(null)}),ie=w(async e=>{if(f.current)return null;v(`metadata`);try{s(null);let n=Re(e),r=e.id?u.current.find(t=>t.id===e.id)??null:null;if(r){let e=n.filter(e=>e.kind===`direct`),t=Ne(r).filter(t=>t.url.startsWith(`https://`)&&!e.some(e=>Ae(e.url,t.url))),i=M(r);n=[...e,...t,...i?[{kind:`relay`,relay:i}]:[]]}if(n.length===0)return s(t(`mobile.connect.error.urlRequired`)),null;let i=e.clientToken?.trim()||void 0,a=e.label?.trim()||ke(N({candidates:n}));if(y()){let e=P({candidates:n});if(i)await U(e,i);else if(r?.hasToken){let t=P(r);if(t&&e&&t!==e){let n=await H(t);n&&await U(e,n)}}}return x({id:e.id,label:a,candidates:n,clientToken:i},!1).find(e=>Fe(e.candidates,n))??null}catch{return s(t(`mobile.connect.history.updateFailed`)),null}finally{b(`metadata`)}}),T=w(async(e,n)=>{if(f.current||!n.trim())return null;let r=u.current.find(t=>t.id===e);if(!r)return null;v(`metadata`),s(null);try{let t={...r,label:n.trim()},i=u.current.map(n=>n.id===e?t:n);return V(i),_(i),t}catch{return s(t(`mobile.connect.history.updateFailed`)),null}finally{b(`metadata`)}}),E=w(async e=>{if(f.current)return null;v(`metadata`),s(null);try{let t=u.current.find(t=>t.id===e)??null,n=await st(e);return _(n),t}catch{return s(t(`mobile.connect.history.updateFailed`)),null}finally{b(`metadata`)}});return{connections:n,isBusy:i!==null,isPasswordBusy:i===`password`,error:o,pendingConnection:c,connect:te,redeemPairingConnection:S,submitPassword:C,cancelPassword:ne,saveConnection:ie,renameConnection:T,removeConnection:E,subscribeConnected:g,setError:s}},Tt=async(e,t=3)=>{let n;for(let r=0;r<t;r+=1)try{await e();return}catch(e){n=e}throw n},Et=async(e,t,n=2)=>{let r=[...new Map(e.map(e=>[e.operationID,e])).values()],i=0;await Promise.all(Array.from({length:Math.min(Math.max(1,n),r.length)},async()=>{for(;i<r.length;){let e=r[i++];try{e.cleanupPhase&&e.cleanupPhase!==`files-released`?await t.cleanup(e.operationID):await t.deliver(e.operationID)}catch{}}}))},Dt=e=>!!(e.serverInstanceID&&e.assistantID&&e.name&&e.avatarSeed&&e.serverLabel&&e.connectionKey),Ot=`yuri.mobile-share.draft-handoff.v1`,kt=`mobile-share-handoff:`,At=20971520,jt=20971520,Mt=e=>`${kt}${e}`,Nt=e=>e??(typeof window>`u`?null:window.localStorage),K=e=>{if(!e)return{};try{let t=JSON.parse(e.getItem(`yuri.mobile-share.draft-handoff.v1`)||`{}`);return Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{let n=typeof t.assistantID==`string`?t.assistantID:Vt(t),r=typeof t.transportIdentity==`string`?t.transportIdentity:t.targetDraftKey?.transportIdentity;if(!n||typeof t.serverInstanceID!=`string`||typeof t.connectionKey!=`string`||!r)return[];let i=t.phase===`cancelled`?`cancelled`:t.phase===`materialized`?`materialized`:`materializing`;return[[e,{...t,draftID:e,assistantID:n,transportIdentity:r,phase:i}]]}))}catch{return{}}},Pt=(e,t)=>{if(!e)return!1;try{return e.setItem(Ot,JSON.stringify(t)),!0}catch{return!1}},Ft=(e,t)=>{let n=K(e);if(delete n[t],e)try{e.setItem(Ot,JSON.stringify(n))}catch{return}},It=(e,t)=>Pt(e,{...K(e),[t.draftID]:t}),Lt=(e,t)=>`native-share:${e}:${t}`,Rt=(e,t)=>t?e?`${e}\n\n${t}`:t:e,zt=e=>e.mime.startsWith(`image/`)&&e.byteSize>0&&e.byteSize<=At,Bt=(e,t)=>!!t?.syntheticParts.some(t=>t.partID===Mt(e.draftID)&&t.text===``&&t.attachments.length===0&&t.synthetic===!0),Vt=e=>{let t=e.targetDraftKey?.owner;return t?.kind!==`surface`||typeof t.ownerID!=`string`||!t.ownerID.startsWith(`assistant:`)?null:t.ownerID.slice(10)||null},Ht=e=>({draftID:e.draftID,serverInstanceID:e.serverInstanceID,connectionKey:e.connectionKey,assistantID:e.assistantID,transportIdentity:e.transportIdentity}),Ut=async(e,t)=>{let n=Nt(t),r=[];for(let t of Object.values(K(n))){if(t.phase===`cancelled`){r.push(Ht(t));continue}if(t.phase===`materialized`)try{await e(t.draftID);let i={...t,phase:`cancelled`};if(!It(n,i))continue;r.push(Ht(i))}catch{continue}}return r},Wt=(e,t)=>{let n=Nt(t),r=K(n)[e.draftID];return!r||r.phase!==`cancelled`||r.serverInstanceID!==e.serverInstanceID||r.connectionKey!==e.connectionKey||r.assistantID!==e.assistantID||r.transportIdentity!==e.transportIdentity?!1:(Ft(n,e.draftID),!K(n)[e.draftID])},Gt=async(e,t)=>{let n=p({transportIdentity:e.transportIdentity},`assistant:${e.assistantID}`),r=t.captureDraftRuntime();if(r.transportIdentity!==e.transportIdentity)return!1;let i=t.getDraft(n),a=Mt(e.draftID);try{if(!i||!i.syntheticParts.some(e=>e.partID===a)){await t.flushDraftPersistence();let n=t.captureDraftRuntime();return n.transportIdentity===e.transportIdentity&&n.generation===r.generation}let o=await t.commitDraftSnapshot({key:n,expectedRevision:i.revision,runtime:r,values:new Map,snapshot:{text:i.text,attachments:i.attachments,syntheticParts:i.syntheticParts.filter(e=>e.partID!==a),mentions:i.mentions,...i.composerReferences===void 0?{}:{composerReferences:i.composerReferences}}});if(!o.current||!o.durable)return!1;await t.flushDraftPersistence();let s=t.captureDraftRuntime();return s.transportIdentity===e.transportIdentity&&s.generation===r.generation}catch{return!1}},Kt=async(e,t)=>{if(e.attachments.length>10||!e.attachments.every(zt)||e.attachments.reduce((e,t)=>e+t.byteSize,0)>jt)throw Error(`invalid_share_attachment`);let n=Nt(t.storage),r=p({transportIdentity:t.transportIdentity},`assistant:${e.assistantID}`),i=K(n)[e.draftID],a=!1;if(!i||g(i.targetDraftKey)!==g(r)){let a=t.input.getDraft(r);if(i={draftID:e.draftID,serverInstanceID:e.serverInstanceID,connectionKey:e.connectionKey,assistantID:e.assistantID,transportIdentity:t.transportIdentity,targetDraftKey:r,baseRevision:a?.revision??`absent`,resultText:Rt(a?.text??``,e.text),attachmentIDs:e.attachments.map((t,n)=>Lt(e.draftID,n)),phase:`materializing`},!It(n,i))throw Error(`handoff_journal_unavailable`)}if(i.phase===`cancelled`)return{durable:!0,cancelled:!0};(i.phase===`materialized`||Bt(i,t.input.getDraft(r)))&&(a=!0);for(let o=0;!a&&o<3;o++){let o=t.input.getDraft(r),s={...i,baseRevision:o?.revision??`absent`,resultText:Rt(o?.text??``,e.text),phase:`materializing`};if(!It(n,s))throw Error(`handoff_journal_unavailable`);i=s;let c=new Map,l=[];for(let n=0;n<e.attachments.length;n++){let r=e.attachments[n],a=i.attachmentIDs[n],o=f(a),s=await t.readAttachment(r);if(s.size!==r.byteSize)throw Error(`staged_file_unavailable`);c.set(o,s.type===r.mime?s:new Blob([s],{type:r.mime})),l.push({attachmentID:a,attachmentRefID:o,filename:r.originalName,mimeType:r.mime,size:r.byteSize,locator:{kind:`blob`,blobID:a},source:`local`})}let u={partID:Mt(e.draftID),text:``,attachments:[],synthetic:!0},d=o?.syntheticParts??[],p=await t.input.commitDraftSnapshot({key:r,expectedRevision:o?.revision??`absent`,runtime:t.input.captureDraftRuntime(),snapshot:{text:i.resultText,attachments:[...o?.attachments??[],...l],syntheticParts:d.some(e=>e.partID===u.partID)?d:[...d,u],mentions:o?.mentions??[],...o?.composerReferences===void 0?{}:{composerReferences:o.composerReferences}},values:c});if(p.durable&&p.current)a=!0;else if(p.status!==`conflict`)throw Error(`draft_handoff_${p.status}`)}if(!a)throw Error(`draft_handoff_conflict`);if(i.phase!==`materialized`&&(i={...i,phase:`materialized`},!It(n,i)))throw Error(`handoff_journal_unavailable`);try{await t.cancelDraft(e.draftID)}catch{return{durable:!0,cancelled:!1}}if(i={...i,phase:`cancelled`},!It(n,i))throw Error(`handoff_journal_unavailable`);return{durable:!0,cancelled:!0}},qt=te(`YuriShare`),Jt=null,Yt=(e,t)=>l()===e&&c()===t,Xt=e=>{if(b()){ue(e);return}let t=le.getState();t.setActiveTab(`assistant`),t.openAssistant(e)},Zt=async()=>{let e=(await qt.pendingAssistantOpen().catch(()=>null))?.request;if(!e)return!1;let t=await dt(e.connectionKey);if(t===`missing`)return await qt.ackAssistantOpen({requestID:e.requestID}).catch(()=>void 0),!0;if(t!==`connected`)return!0;let n=c();if(!Yt(e.connectionKey,n))return!0;try{let[t,r]=await Promise.all([T(),E()]);if(!Yt(e.connectionKey,n))return!0;let i=r.assistants.some(t=>t.id===e.assistantID&&t.enabled);if(!t.supported||!t.enabled||t.serverInstanceID!==e.serverInstanceID||!i)return await qt.ackAssistantOpen({requestID:e.requestID}),!0;Xt(e.assistantID),await qt.ackAssistantOpen({requestID:e.requestID})}catch{}return!0},q=async()=>S.getPlatform()===`android`?Jt||(Jt=Zt().finally(()=>{Jt=null}),Jt):!1,Qt=e=>({displayName:e}),J=v();function $t(e){let t=(0,_e.c)(30),{draft:n,entries:r,busy:i,onSelect:a,onCancel:o}=e,{t:s}=re(),c;t[0]!==i||t[1]!==n||t[2]!==o?(c=()=>{n&&!i&&o(n)},t[0]=i,t[1]=n,t[2]=o,t[3]=c):c=t[3];let l=w(c),u;t[4]===l?u=t[5]:(u=e=>{e||l()},t[4]=l,t[5]=u);let d=w(u),f;t[6]!==n||t[7]!==a?(f=e=>{n&&a(n,e)},t[6]=n,t[7]=a,t[8]=f):f=t[8];let p=w(f),m=!!n,h;t[9]===s?h=t[10]:(h=s(`assistants.shareWelcome.example.note.title`),t[9]=s,t[10]=h);let g;t[11]===s?g=t[12]:(g=s(`settings.common.actions.cancel`),t[11]=s,t[12]=g);let _;t[13]!==i||t[14]!==l||t[15]!==h||t[16]!==g?(_=(0,J.jsx)(se,{title:h,backAriaLabel:g,onBack:l,backDisabled:i,overlay:!0}),t[13]=i,t[14]=l,t[15]=h,t[16]=g,t[17]=_):_=t[17];let v;t[18]!==i||t[19]!==r||t[20]!==p||t[21]!==s?(v=r.length?(0,J.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto px-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] pt-[calc(max(0.25rem,var(--yuri-safe-area-top,0px))+var(--yuri-mobile-detail-navigation-height,3.5rem)+0.75rem)]`,role:`listbox`,"aria-label":s(`assistants.listAria`),children:r.map(e=>{let t=Qt(e.name).displayName||e.name;return(0,J.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":`false`,disabled:i,className:`flex w-full items-center gap-3 border-b border-border/60 px-3 py-4 text-left text-foreground transition-colors last:border-b-0 hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-60`,onClick:()=>p(e),children:[(0,J.jsx)(fe,{kind:`assistant`,name:e.avatarSeed,size:40,label:t,shape:`rounded`,className:`rounded-[0.5rem]`}),(0,J.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,J.jsx)(`span`,{className:`block truncate font-semibold`,children:t}),(0,J.jsx)(`span`,{className:`block truncate typography-small text-muted-foreground`,children:e.serverLabel})]}),(0,J.jsx)(pe,{name:`arrow-right-s`,className:`size-4 shrink-0 text-muted-foreground`})]},`${e.connectionKey}:${e.assistantID}`)})}):(0,J.jsx)(`p`,{className:`px-5 pb-[max(1.25rem,env(safe-area-inset-bottom))] pt-[calc(max(0.25rem,var(--yuri-safe-area-top,0px))+var(--yuri-mobile-detail-navigation-height,3.5rem)+0.75rem)] typography-ui text-muted-foreground`,children:s(`assistants.state.unavailable`)}),t[18]=i,t[19]=r,t[20]=p,t[21]=s,t[22]=v):v=t[22];let y;t[23]!==_||t[24]!==v?(y=(0,J.jsxs)(me,{className:`h-[100dvh] max-h-none w-screen max-w-none gap-0 overflow-hidden rounded-none border-0 bg-background p-0`,containerClassName:`items-stretch p-0`,overlayClassName:`bg-background`,showCloseButton:!1,children:[_,v]}),t[23]=_,t[24]=v,t[25]=y):y=t[25];let b;return t[26]!==d||t[27]!==m||t[28]!==y?(b=(0,J.jsx)(he,{open:m,onOpenChange:d,children:y}),t[26]=d,t[27]=m,t[28]=y,t[29]=b):b=t[29],b}var en=e({MobileShareBridge:()=>Fn,donateNativeAssistantInteraction:()=>wn,publishNativeAssistantCatalog:()=>Cn,refreshNativeAssistantCatalog:()=>Q}),Y=te(`YuriShare`),tn=`yuri.mobile-share.outbox.v1`,nn=()=>S.isNativePlatform(),rn=()=>{try{return JSON.parse(window.localStorage.getItem(tn)||`{}`)}catch{return{}}},an=e=>{try{window.localStorage.setItem(tn,JSON.stringify(e))}catch{}},X=e=>{let t=rn(),n=t[e.envelope.operationID];n&&n.updatedAt>e.updatedAt||(t[e.envelope.operationID]=e,an(t))},Z=(e,t)=>l()===e&&c()===t,on=new Map,sn=null,cn=null,ln=!1,un=[],dn=0,fn=new Set,pn=new Map,mn=1,hn=e=>{e.map(e=>e.draftID).join(`
|
|
3
|
-
`)!==un.map(e=>e.draftID).join(`
|
|
4
|
-
`)&&(un=e,dn+=1,fn.forEach(e=>e()))},gn=e=>hn(un.filter(t=>t.draftID!==e)),_n=e=>(fn.add(e),()=>fn.delete(e)),vn=()=>dn,yn=async e=>{if(!e.mime.startsWith(`image/`))throw Error(`unsupported_share_attachment`);let t=e.stagedPath.trim();if(!t)throw Error(`staged_file_unavailable`);let n=/^(?:data:|https?:|content:|file:)/i.test(t)?t:`file://${t}`,r=/^(?:data:|https?:)/i.test(n)?n:S.convertFileSrc(n);return x(()=>fetch(r).then(e=>{if(!e.ok)throw Error(`staged_file_unavailable`);return e.blob()}))},bn=async e=>{let t=await yn(e);return await new Promise((e,n)=>{let r=new FileReader;r.onerror=()=>n(Error(`staged_file_unavailable`)),r.onload=()=>typeof r.result==`string`?e(r.result):n(Error(`staged_file_unavailable`)),r.readAsDataURL(t)})},xn=async e=>{let t=[];if(e.text?.trim()&&t.push({type:`text`,text:e.text}),e.attachments.length>10)throw Error(`too_many_share_attachments`);for(let n of e.attachments){if(n.byteSize<=0||n.byteSize>20971520)throw Error(`invalid_share_attachment`);t.push({type:`file`,mime:n.mime,url:await bn(n)})}if(t.length===0)throw Error(`empty_share`);return t},Q=async()=>{if(!nn())return;let e=l(),t=(await at()).find(t=>Pe(t)===e);if(!t)return;let n=c();try{let[r,i]=await Promise.all([T(),oe()]);if(!Z(e,n)||!r.supported||!r.serverInstanceID)return;let a=r.serverInstanceID,o=i.assistants.map(n=>({serverInstanceID:a,assistantID:n.id,name:n.name,avatarSeed:n.avatarSeed??n.id,serverLabel:t.label,connectionKey:e,enabled:r.enabled&&n.enabled,isDefaultShareTarget:!1}));O.getState().replaceCatalogPartition({serverInstanceID:a,connectionKey:e,revision:i.revision,lastLoadedAt:Date.now(),entries:o}),await Cn()}catch{}},Sn=0,Cn=async()=>{if(!nn())return;let e=++Sn,t=[];for(let n of Object.values(O.getState().assistantCatalogByConnection).flatMap(e=>e.entries)){let r=Qt(n.name),i=await ge(de(`assistant`,n.avatarSeed),128);if(e!==Sn)return;t.push({...n,name:r.displayName||n.name,...i?{avatarPng:i}:{}})}await Y.updateCatalog({entries:t})},wn=async e=>{if(S.getPlatform()!==`ios`)return;let t=await ge(de(`assistant`,e.avatarSeed),128);await Y.donateAssistantInteraction({...e,...t?{avatarPng:t}:{}})},Tn=e=>{let t=on.get(e.operationID);if(t)return t;let n=Dn(e);return on.set(e.operationID,n),n.finally(()=>{on.get(e.operationID)===n&&on.delete(e.operationID)}).catch(()=>void 0),n},En=async e=>{e.cleanupPhase!==`files-released`&&(e.cleanupPhase===`server-completed`&&(await Tt(()=>Y.ack({operationID:e.envelope.operationID})),e={...e,state:`delivered`,cleanupPhase:`native-acked`,updatedAt:Date.now()},X(e)),e.cleanupPhase===`native-acked`&&(await Tt(()=>Y.releaseFiles({operationID:e.envelope.operationID})),X({...e,state:`delivered`,cleanupPhase:`files-released`,updatedAt:Date.now()})))},Dn=async e=>{let t=rn()[e.operationID];if(t?.cleanupPhase){await En(t);return}let n=t?.messageID?t:{envelope:e,messageID:m(`msg`),state:t?.state??`pending`,cleanupPhase:t?.cleanupPhase,updatedAt:Date.now(),error:t?.error};X(n),n={...n,state:`resolving-instance`,updatedAt:Date.now()},X(n);let r=Object.values(O.getState().assistantCatalogByConnection).find(t=>t.serverInstanceID===e.serverInstanceID&&t.entries.some(t=>t.assistantID===e.assistantID));if(!r){X({...n,state:`target-stale`,updatedAt:Date.now()});return}n={...n,state:`connecting`,updatedAt:Date.now()},X(n);let i=await dt(r.connectionKey);if(i===`auth-required`){X({...n,state:`auth-required`,updatedAt:Date.now()});return}if(i!==`connected`){X({...n,state:`offline`,updatedAt:Date.now()});return}let a=c(),s=null;if(Z(r.connectionKey,a)){try{if(await d(`/api/config/settings`).catch(()=>void 0),!Z(r.connectionKey,a))return;let[t,i]=await Promise.all([T(),oe()]);if(!Z(r.connectionKey,a)||!t.supported||t.serverInstanceID!==e.serverInstanceID){X({...n,state:`target-stale`,updatedAt:Date.now()});return}let c=i.assistants.find(t=>t.id===e.assistantID&&t.enabled);if(!t.enabled||!c){X({...n,state:`target-stale`,updatedAt:Date.now()});return}n={...n,state:`dispatching`,updatedAt:Date.now()},X(n);let l=await xn(e);if(!Z(r.connectionKey,a))return;n={...n,state:`reconciling`,updatedAt:Date.now()},X(n);let u=await ae(c.id,e.operationID,n.messageID,l,e.source),f=await ce(u,o(),a),p=await E().catch(e=>(X({...n,state:`reconciling`,updatedAt:Date.now(),error:e instanceof Error?e.message:`snapshot_refresh_failed`}),null));if(!p)return;if(!Z(r.connectionKey,a)){X({...n,state:`reconciling`,updatedAt:Date.now(),error:`runtime_stale`});return}let m=p.assistants.find(e=>e.id===c.id);if(!m||m.sessionID!==f.sessionID){X({...n,state:`reconciling`,updatedAt:Date.now(),error:`assistant_binding_mismatch`});return}s=m.id}catch(e){if(e instanceof ie&&e.code===`share_unresolved`||e instanceof Error&&e.message===`runtime_stale`){X({...n,state:`reconciling`,updatedAt:Date.now(),error:e instanceof Error?e.message:`share_unresolved`});return}X({...n,state:`failed`,updatedAt:Date.now(),error:e instanceof Error?e.message:`dispatch_failed`});return}n={...n,state:`delivered`,cleanupPhase:`server-completed`,updatedAt:Date.now()},X(n),Xt(s),await En(n)}},On=async()=>sn||(sn=kn().finally(()=>{sn=null}),sn),kn=async()=>{if(!nn())return;let e=await Y.listPending().catch(()=>null),t=new Map((e?.envelopes??[]).map(e=>[e.operationID,e])),n=rn();await Et([...[...t.values()].map(e=>({operationID:e.operationID,cleanupPhase:n[e.operationID]?.cleanupPhase})),...Object.values(n).filter(e=>!t.has(e.envelope.operationID)&&(!!(e.cleanupPhase&&e.cleanupPhase!==`files-released`)||e.state!==`delivered`&&e.state!==`auth-required`&&e.state!==`target-stale`)).map(e=>({operationID:e.envelope.operationID,cleanupPhase:e.cleanupPhase}))],{deliver:async e=>{let r=t.get(e)??n[e]?.envelope;r&&await Tn(r)},cleanup:async e=>{let t=rn()[e];t&&await En(t)}},mn)},$=async()=>(ln=!0,cn||(cn=(async()=>{do ln=!1,await Pn();while(ln)})().finally(()=>{cn=null,ln&&$()}),cn)),An=async e=>{if(l()!==e.connectionKey&&await dt(e.connectionKey)!==`connected`)return!1;let t=c();if(!Z(e.connectionKey,t)||o()!==e.transportIdentity||(await d(`/api/config/settings`).catch(()=>void 0),!Z(e.connectionKey,t)||o()!==e.transportIdentity)||!await D.getState().hydrateDraftMetadata(e.transportIdentity)||!Z(e.connectionKey,t)||o()!==e.transportIdentity)return!1;let[n,r]=await Promise.all([T(),E()]);return!Z(e.connectionKey,t)||o()!==e.transportIdentity||!n.supported||!n.enabled||n.serverInstanceID!==e.serverInstanceID||!r.assistants.some(t=>t.id===e.assistantID&&t.enabled)?!1:(Xt(e.assistantID),!0)},jn=async e=>{let t=l(),n=c();if(await d(`/api/config/settings`).catch(()=>void 0),!Z(t,n))return null;try{let[r,i]=await Promise.all([T(),E()]);return!Z(t,n)||!r.supported||!r.enabled||r.serverInstanceID!==e.serverInstanceID||!i.assistants.some(t=>t.id===e.assistantID&&t.enabled)?null:{runtimeKey:t,generation:n,transportIdentity:o()}}catch{return null}},Mn=async e=>{let t=Object.values(O.getState().assistantCatalogByConnection).find(t=>t.serverInstanceID===e.serverInstanceID&&t.connectionKey===e.connectionKey&&t.entries.some(t=>t.assistantID===e.assistantID));if(!t)return!1;let n=await jn(e);if(!n&&(await dt(t.connectionKey,{transportPreference:`relay`})!==`connected`||(n=await jn(e),!n)))return!1;let{runtimeKey:r,generation:i,transportIdentity:a}=n;if(!await D.getState().hydrateDraftMetadata(a)||!Z(r,i)||o()!==a)return!1;let s=await Kt(e,{input:D.getState(),transportIdentity:a,cancelDraft:e=>Y.cancelDraft({draftID:e}),readAttachment:yn});if(!s.durable||!s.cancelled||!Z(r,i)||o()!==a)return!1;let c={draftID:e.draftID,serverInstanceID:e.serverInstanceID,connectionKey:e.connectionKey,assistantID:e.assistantID,transportIdentity:a};return Xt(e.assistantID),await Gt(c,D.getState())&&Wt(c),!0},Nn=e=>{let t=pn.get(e.draftID);if(t)return t;let n=Mn(e).catch(()=>!1).finally(()=>{pn.get(e.draftID)===n&&pn.delete(e.draftID)});return pn.set(e.draftID,n),n},Pn=async()=>{if(S.getPlatform()!==`android`)return;let e=await Ut(e=>Y.cancelDraft({draftID:e}));for(let t of e)try{await An(t)&&await Gt(t,D.getState())&&Wt(t)}catch{}let t=await Y.listDrafts().catch(()=>null);if(!t)return;let n=[...t?.drafts??[]].sort((e,t)=>e.createdAt-t.createdAt);hn(n.filter(e=>!Dt(e)));for(let e of n)Dt(e)&&await Nn(e)},Fn=()=>{let e=(0,_e.c)(11);k.useSyncExternalStore(_n,vn,vn);let t=O(In),[n,r]=k.useState(null),i=k.useRef(null),a;e[0]===t?a=e[1]:(a=Object.values(t).flatMap(Ln).filter(Rn).sort(zn),e[0]=t,e[1]=a);let o=a,s=un[0]??null,c;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(c=(e,t)=>{i.current||(i.current=e.draftID,r(e.draftID),Nn({...e,serverInstanceID:t.serverInstanceID,assistantID:t.assistantID,name:t.name,avatarSeed:t.avatarSeed,serverLabel:t.serverLabel,connectionKey:t.connectionKey}).then(t=>{t&&gn(e.draftID)}).finally(()=>{i.current===e.draftID&&(i.current=null),r(t=>t===e.draftID?null:t)}))},e[2]=c):c=e[2];let l=w(c),u;e[3]===n?u=e[4]:(u=e=>{n!==e.draftID&&(gn(e.draftID),Y.cancelDraft({draftID:e.draftID}).catch(Bn))},e[3]=n,e[4]=u);let d=w(u),f;e[5]===Symbol.for(`react.memo_cache_sentinel`)?(f=[],e[5]=f):f=e[5],k.useEffect(Yn,f);let p=n===s?.draftID,m;return e[6]!==d||e[7]!==o||e[8]!==l||e[9]!==p?(m=(0,J.jsx)($t,{draft:s,entries:o,busy:p,onSelect:l,onCancel:d}),e[6]=d,e[7]=o,e[8]=l,e[9]=p,e[10]=m):m=e[10],m};function In(e){return e.assistantCatalogByConnection}function Ln(e){return e.entries}function Rn(e){return e.enabled}function zn(e,t){return Number(t.isDefaultShareTarget)-Number(e.isDefaultShareTarget)||e.serverLabel.localeCompare(t.serverLabel)||e.name.localeCompare(t.name)}function Bn(){$()}function Vn(){Q(),$(),q()}function Hn(){Q(),On(),$(),q()}function Un(){On()}function Wn(){}function Gn(){$()}function Kn(){}function qn(){q()}function Jn(){}function Yn(){if(!nn())return;Q(),On(),$(),q();let e=a(Vn),t=Hn;window.addEventListener(`yuri:system-resume`,t);let n=!1,r=null,i=null,o=null;return Y.addListener(`shareReceived`,Un).then(e=>{n?e.remove():r=e}).catch(Wn),Y.addListener(`shareDraftReceived`,Gn).then(e=>{n?e.remove():i=e}).catch(Kn),Y.addListener(`assistantOpenRequested`,qn).then(e=>{n?e.remove():o=e}).catch(Jn),()=>{n=!0,e(),window.removeEventListener(`yuri:system-resume`,t),r&&r.remove(),i&&i.remove(),o&&o.remove()}}export{Qt as a,N as c,at as d,Pe as f,Q as i,lt as l,wt as m,wn as n,q as o,yt as p,Cn as r,ut as s,Fn as t,vt as u};
|