diff --git a/design-system/AGENTS.md b/design-system/AGENTS.md index 5765e30c91..7c4f63f4ed 100644 --- a/design-system/AGENTS.md +++ b/design-system/AGENTS.md @@ -106,3 +106,9 @@ OPENBITFUN_WORKBENCH_MOTION_CONTRACT=1 OPENBITFUN_MOTION_REFERENCE_COMMIT=HEAD O Use a pre-change reference commit when testing an already committed change. The native fixture runs outside performance windows. Geometry equivalence does not establish pixel-identical rasterization or coverage on other WebView engines. + +For shared queue pointer/keyboard interaction, cancellation and focus retention: + +```bash +pnpm --dir src/web-ui exec vitest run src/flow_chat/components/useQueueReorder.test.tsx +``` diff --git a/design-system/packages/ui/README.md b/design-system/packages/ui/README.md index a481a94d89..cfcf3e242e 100644 --- a/design-system/packages/ui/README.md +++ b/design-system/packages/ui/README.md @@ -1040,3 +1040,12 @@ Checkbox, Select, Combobox, MultiSelect, NumberInput, SearchField and Textarea consume those references through intervening wrappers. A control's explicit name or own label takes precedence; descriptions are combined. Give each child in a composite field its own name. Nested `Field` controls retain their own labels. + +`ChatComposerQueue` has no outer border. Each row starts with an inset hairline; +the final row has no bottom hairline and meets the composer without an extra +gap. `ChatComposerQueueItem.leadingControl` accepts an accessible interactive +control; `leadingIcon` remains decorative. `useQueueReorder` supplies pointer +capture, keyboard moves, edge scrolling and cancellation when the authoritative +revision changes. Pass only reorderable IDs and keep the actual order in the +product owner until its mutation succeeds. Disabled or legacy hosts must expose +a clear reason in their product surface. diff --git a/design-system/packages/ui/src/flow-chat/composer/ChatComposer.module.css b/design-system/packages/ui/src/flow-chat/composer/ChatComposer.module.css index 103fc794cc..7e5d0f14a4 100644 --- a/design-system/packages/ui/src/flow-chat/composer/ChatComposer.module.css +++ b/design-system/packages/ui/src/flow-chat/composer/ChatComposer.module.css @@ -32,6 +32,10 @@ gap: var(--openbitfun-space-2); } + .body:has(> .queue > :global([data-openbitfun-component="chat-composer-queue"])) { + gap: 0; + } + .queue { /* The wrapper exists when a queue component later renders `null`. Keeping it out of the box tree makes both that transition and the no-queue path diff --git a/design-system/packages/ui/src/flow-chat/composer/ChatComposerQueue.module.css b/design-system/packages/ui/src/flow-chat/composer/ChatComposerQueue.module.css index 8efefc5a28..9ca741bb74 100644 --- a/design-system/packages/ui/src/flow-chat/composer/ChatComposerQueue.module.css +++ b/design-system/packages/ui/src/flow-chat/composer/ChatComposerQueue.module.css @@ -8,24 +8,13 @@ inline-size: 100%; flex-direction: column; gap: var(--openbitfun-space-1); - padding: var(--openbitfun-space-1); - border: var(--openbitfun-border-width-default) solid var(--openbitfun-color-border-subtle); - border-radius: var(--openbitfun-control-composer-surface-radius); + padding: var(--openbitfun-space-1) var(--openbitfun-space-1) 0; + border: 0; + border-radius: 0; container: composer-queue / inline-size; color: var(--openbitfun-color-content-primary); - background: var(--openbitfun-color-surface-subtle); - font-family:var(--openbitfun-type-body-md-font-family); - } - - /* A composer with a context bar already tints the tray around its input. - The queue joins that tray instead of stacking a second translucent card. */ - :global([data-openbitfun-component="chat-composer"][data-has-context="true"]) .root { - margin-block-end: calc(-1 * var(--openbitfun-space-2)); - padding-block-end: var(--openbitfun-space-3); - border-block-end: 0; - border-end-start-radius: 0; - border-end-end-radius: 0; background: transparent; + font-family:var(--openbitfun-type-body-md-font-family); } .header { @@ -102,6 +91,7 @@ } .item { + position: relative; box-sizing: border-box; display: flex; flex: 0 0 auto; @@ -114,6 +104,29 @@ color: var(--openbitfun-color-content-primary); } + .item::before { + content: ""; + position: absolute; + inset-inline: var(--openbitfun-space-2); + inset-block-start: 0; + border-block-start: var(--openbitfun-border-width-default) solid var(--openbitfun-color-border-subtle); + pointer-events: none; + } + + .item[data-queue-dragging] { + z-index: 1; + background: var(--openbitfun-color-surface-panel); + box-shadow: var(--openbitfun-shadow-sm); + } + .item[data-queue-drop="before"] { box-shadow: inset 0 2px var(--openbitfun-color-focus-ring); } + .item[data-queue-drop="after"] { box-shadow: inset 0 -2px var(--openbitfun-color-focus-ring); } + .item [data-queue-handle] { + cursor: grab; + touch-action: none; + user-select: none; + } + .item [data-queue-handle]:active { cursor: grabbing; } + /* The row, not a floating button cluster, is the unit being acted on. */ .item:focus-within { background: var(--openbitfun-color-surface-subtle); @@ -223,6 +236,8 @@ .actions [data-openbitfun-component="button"][data-openbitfun-variant="text"] { flex: 1 1 0; min-inline-size: 0; + justify-content: flex-start; + text-align: start; color: var(--openbitfun-color-content-secondary); padding-inline: var(--openbitfun-space-2); } @@ -237,6 +252,9 @@ .actions { --_queue-primary-action-size: var(--_queue-action-size); } + .actions [data-openbitfun-component="button"][data-openbitfun-variant="text"] { + justify-content: center; + } .actions [data-openbitfun-component="button"] [data-openbitfun-part="label"] { display: none; } @@ -252,8 +270,6 @@ } @media (forced-colors: active) { - .root { - border: var(--openbitfun-border-width-default) solid CanvasText; - } + .item::before { border-color: CanvasText; } } } diff --git a/design-system/packages/ui/src/flow-chat/composer/ChatComposerQueue.tsx b/design-system/packages/ui/src/flow-chat/composer/ChatComposerQueue.tsx index 925f55d0eb..beb8701faa 100644 --- a/design-system/packages/ui/src/flow-chat/composer/ChatComposerQueue.tsx +++ b/design-system/packages/ui/src/flow-chat/composer/ChatComposerQueue.tsx @@ -38,6 +38,8 @@ export interface ChatComposerQueueItemProps extends LiHTMLAttributes { state?: ChatComposerQueueItemState; leadingIcon?: ReactNode; + /** Interactive leading slot; unlike leadingIcon it remains accessible. */ + leadingControl?: ReactNode; } export interface ChatComposerQueueItemContentProps @@ -159,7 +161,7 @@ export const ChatComposerQueueList = forwardRef< export const ChatComposerQueueItem = forwardRef< HTMLLIElement, ChatComposerQueueItemProps ->(function ChatComposerQueueItem({ children, className, leadingIcon, state = "default", ...props }, ref) { +>(function ChatComposerQueueItem({ children, className, leadingIcon, leadingControl, state = "default", ...props }, ref) { return (
  • - {leadingIcon && } + {leadingControl && {leadingControl}} + {!leadingControl && leadingIcon && } {children}
  • ); diff --git a/design-system/packages/ui/src/flow-chat/composer/index.ts b/design-system/packages/ui/src/flow-chat/composer/index.ts index b5e17cb096..56e00f6c52 100644 --- a/design-system/packages/ui/src/flow-chat/composer/index.ts +++ b/design-system/packages/ui/src/flow-chat/composer/index.ts @@ -35,3 +35,5 @@ export { type ChatComposerQueueTitleProps, type ChatComposerQueueToggleProps, } from "./ChatComposerQueue"; + +export { useQueueReorder } from './useQueueReorder'; diff --git a/design-system/packages/ui/src/flow-chat/composer/useQueueReorder.ts b/design-system/packages/ui/src/flow-chat/composer/useQueueReorder.ts new file mode 100644 index 0000000000..18844d0b4b --- /dev/null +++ b/design-system/packages/ui/src/flow-chat/composer/useQueueReorder.ts @@ -0,0 +1,146 @@ +import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react'; + +type Drag = { + id: string; + startY: number; + pointerY: number; + pointerId: number; + handle: HTMLButtonElement; + order: string[]; + revision: string | number; + before: string | null; + scroller: HTMLElement; + scrollTop: number; + moved: boolean; +}; + +/** Pointer/keyboard presentation only. The caller owns authoritative ordering. */ +export function useQueueReorder(ids: string[], enabled: boolean, revision: string | number, + onMove: (id: string, beforeId: string | null) => void) { + const rows = useRef(new Map()); + const drag = useRef(null); + const frame = useRef(null); + const focusAfterMove = useRef(null); + const [visual, setVisual] = useState<{ id: string; y: number; before: string | null } | null>(null); + const identity = ids.join('\0'); + const latest = useRef({ enabled, revision, identity, onMove }); + latest.current = { enabled, revision, identity, onMove }; + + const requestMove = (id: string, before: string | null) => { + focusAfterMove.current = id; + latest.current.onMove(id, before); + }; + const stopFrame = () => { + if (frame.current !== null) cancelAnimationFrame(frame.current); + frame.current = null; + }; + const finish = (commit: boolean) => { + const current = drag.current; + drag.current = null; + stopFrame(); + setVisual(null); + if (!current) return; + if (current.handle.hasPointerCapture?.(current.pointerId)) current.handle.releasePointerCapture(current.pointerId); + const originalBefore = current.order[current.order.indexOf(current.id) + 1] ?? null; + if (commit && current.moved && current.before !== originalBefore && latest.current.enabled + && latest.current.revision === current.revision && latest.current.identity === current.order.join('\0')) { + requestMove(current.id, current.before); + } + }; + useEffect(() => { + finish(false); + if (enabled && focusAfterMove.current) { + const handle = rows.current.get(focusAfterMove.current)?.querySelector('[data-queue-handle]'); + // Disabling controls during a host mutation can move focus to the body. + // Restore the moved row, but do not interrupt a user who moved elsewhere. + if (handle && !handle.disabled && (document.activeElement === document.body || document.activeElement === handle)) handle.focus(); + focusAfterMove.current = null; + } + }, [identity, enabled, revision]); + useEffect(() => { + const cancel = (event: KeyboardEvent) => { + if (event.key === 'Escape' && drag.current) { event.preventDefault(); finish(false); } + }; + const blur = () => finish(false); + window.addEventListener('keydown', cancel); + window.addEventListener('blur', blur); + return () => { + window.removeEventListener('keydown', cancel); + window.removeEventListener('blur', blur); + const current = drag.current; + drag.current = null; + stopFrame(); + if (current?.handle.hasPointerCapture?.(current.pointerId)) current.handle.releasePointerCapture(current.pointerId); + }; + }, []); + + const paint = (current: Drag) => { + current.before = current.order.find(id => { + if (id === current.id) return false; + const row = rows.current.get(id); + if (!row) return false; + const rect = row.getBoundingClientRect(); + return current.pointerY < rect.top + rect.height / 2; + }) ?? null; + setVisual({ id: current.id, y: current.pointerY - current.startY + current.scroller.scrollTop - current.scrollTop, before: current.before }); + }; + const scrollFrame = () => { + frame.current = null; + const current = drag.current; + if (!current?.moved) return; + const bounds = current.scroller.getBoundingClientRect(); + const speed = current.pointerY < bounds.top + 24 ? -6 : current.pointerY > bounds.bottom - 24 ? 6 : 0; + const previous = current.scroller.scrollTop; + if (speed) current.scroller.scrollTop += speed; + if (previous !== current.scroller.scrollTop) paint(current); + if (speed) frame.current = requestAnimationFrame(scrollFrame); + }; + const update = (event: ReactPointerEvent) => { + const current = drag.current; + if (!current || current.pointerId !== event.pointerId) return; + current.pointerY = event.clientY; + current.moved ||= Math.abs(event.clientY - current.startY) > 4; + if (!current.moved) return; + paint(current); + if (frame.current === null) frame.current = requestAnimationFrame(scrollFrame); + }; + return { + rowProps(id: string) { + return { + ref: (node: HTMLLIElement | null) => { if (node) rows.current.set(id, node); else rows.current.delete(id); }, + 'data-queue-dragging': visual?.id === id || undefined, + 'data-queue-drop': visual && visual.id !== id && (visual.before === id ? 'before' + : visual.before === null && id === ids.filter(value => value !== visual.id).slice(-1)[0] ? 'after' : undefined), + style: visual?.id === id ? { transform: `translateY(${visual.y}px)` } as CSSProperties : undefined, + }; + }, + handleProps(id: string) { + return { + 'data-queue-handle': true, + disabled: !enabled || ids.length < 2 || !ids.includes(id), + onPointerDown(event: ReactPointerEvent) { + if (!enabled || ids.length < 2 || !ids.includes(id) || event.button !== 0 || drag.current) return; + const row = rows.current.get(id); + if (!row?.parentElement) return; + event.preventDefault(); + event.currentTarget.focus(); + event.currentTarget.setPointerCapture(event.pointerId); + drag.current = { id, startY: event.clientY, pointerY: event.clientY, pointerId: event.pointerId, + handle: event.currentTarget, order: [...ids], revision, before: ids[ids.indexOf(id) + 1] ?? null, + scroller: row.parentElement, scrollTop: row.parentElement.scrollTop, moved: false }; + }, + onPointerMove: update, + onPointerUp: (event: ReactPointerEvent) => { if (drag.current?.pointerId === event.pointerId) finish(true); }, + onPointerCancel: () => finish(false), + onLostPointerCapture: () => finish(false), + onKeyDown(event: ReactKeyboardEvent) { + if (!enabled || drag.current || !['ArrowUp', 'ArrowDown'].includes(event.key)) return; + event.preventDefault(); + const index = ids.indexOf(id); + if (event.key === 'ArrowUp' && index > 0) requestMove(id, ids[index - 1]!); + if (event.key === 'ArrowDown' && index >= 0 && index < ids.length - 1) requestMove(id, ids[index + 2] ?? null); + }, + }; + }, + }; +} diff --git a/design-system/packages/ui/tests/chat-composer.test.mjs b/design-system/packages/ui/tests/chat-composer.test.mjs index 00031e7d16..a00797492e 100644 --- a/design-system/packages/ui/tests/chat-composer.test.mjs +++ b/design-system/packages/ui/tests/chat-composer.test.mjs @@ -213,7 +213,7 @@ test("ChatComposer queue keeps actions visible and message ink primary", async ( assert.ok(actionsRule); assert.ok(contentRule); assert.match(actionsRule, /display:\s*inline-flex/); - assert.doesNotMatch(styles, /pointer-events:\s*none|opacity:\s*0(?:;|\s)/); + assert.doesNotMatch(actionsRule, /pointer-events:\s*none|opacity:\s*0(?:;|\s)/); assert.match(contentRule, /color:\s*var\(--openbitfun-color-content-primary\)/); assert.match(styles, /@media \(hover: hover\) and \(pointer: fine\)/); assert.match(styles, /\.item:focus-within\s*\{[^}]*background:/s); @@ -249,7 +249,7 @@ test("ChatComposer queue never changes the input surface geometry", async () => assert.match(bodyRule, /gap:\s*var\(--openbitfun-space-2\)/); assert.ok(queueRule); assert.match(queueRule, /display:\s*contents/); - assert.doesNotMatch(styles, /\.body:has\(/); + assert.match(styles, /\.body:has\([^}]*chat-composer-queue[^}]*gap:\s*0/); assert.doesNotMatch(styles, /\.queue:empty/); }); diff --git a/src/apps/cli/AGENTS.md b/src/apps/cli/AGENTS.md index e1280cda31..e3ce230805 100644 --- a/src/apps/cli/AGENTS.md +++ b/src/apps/cli/AGENTS.md @@ -232,3 +232,12 @@ Native provider and OS fixture checks belong to [`services/computer-use`](../../crates/services/computer-use/AGENTS.md). CLI owns the main-thread run-loop adapter and provider injection, including Shared TUI's executing host. Dispatch, ACP and the stdio server do not infer a GUI provider. + +For `/queue` keyboard mutations, legacy capability gates and compact rendering: + +```bash +cargo test --locked -p openbitfun-cli --bin openbitfun ui::message_queue::tests +``` + +The selector uses the typed runtime port through `CliAgentRuntimeClient`. +Shared TUI reports unsupported until its IPC contract negotiates queue support. diff --git a/src/apps/cli/README.md b/src/apps/cli/README.md index a1f4f28fd3..1c5c680b5c 100644 --- a/src/apps/cli/README.md +++ b/src/apps/cli/README.md @@ -94,6 +94,7 @@ equivalent exists: | --- | --- | | `/sessions` | Browse and restore sessions. | | `/new` or `/clear` | Start a new session. | +| `/queue` | Manage the current session’s pending messages on the embedded runtime. | | `/timeline` | Navigate persisted user messages without changing the session. | | `/fork` | Fork the full session or fork immediately before a selected prompt. | | `/goal ` | Start a persistent goal through the shared runtime; while working, steer the active turn toward it. | @@ -117,6 +118,18 @@ selected child Session's active execution subtree. configure a command that waits until the file is closed; missing commands, non-zero exits, and empty editor output leave the current draft unchanged. +### Pending messages + +`/queue` displays the execution host's pending messages. Use Up/Down to select, +Shift+Up/Down to reorder, Enter to send now, Delete to remove, and `r` to refresh. +The visible list refreshes every two seconds and changes only after the host confirms the operation. Failed requests +retain the visible list and require a refresh before another mutation. Sending +now hands off after the current atomic action; removing a pending message does +not cancel the active turn. + +Shared TUI currently reports queue management as unsupported. Queue controls do +not change normal running-turn input or Detached Dispatch behavior. + ### Long-running goals A prompt beginning with `/goal ` activates the goal on the executing diff --git a/src/apps/cli/src/actions.rs b/src/apps/cli/src/actions.rs index 58c42d7366..c5ebcaa4f1 100644 --- a/src/apps/cli/src/actions.rs +++ b/src/apps/cli/src/actions.rs @@ -106,6 +106,7 @@ pub(crate) enum ActionHandler { PromptStash, PromptStashPop, PromptStashList, + MessageQueue, ToggleTimestamps, ToggleThinking, ToggleToolDetails, @@ -174,6 +175,7 @@ impl ActionHandler { | Self::PromptStash | Self::PromptStashPop | Self::PromptStashList + | Self::MessageQueue | Self::ToggleTimestamps | Self::ToggleThinking | Self::ToggleToolDetails @@ -751,6 +753,21 @@ static ACTION_SPECS: &[ActionSpec] = &[ shortcut_label: None, slash_on_startup: false, }, + ActionSpec { + id: "message_queue", + name: "Queued messages", + aliases: &["/queue"], + description: "Inspect, reorder, send or remove queued messages", + contexts: CHAT, + availability: ActionAvailability::Always, + handler: ActionHandler::MessageQueue, + default_bindings: &[], + fallback_bindings: &[], + shortcut_field: None, + palette: palette("Prompt", false), + shortcut_label: None, + slash_on_startup: false, + }, ActionSpec { id: "prompt_stash", name: "Stash prompt", diff --git a/src/apps/cli/src/agent/runtime_client.rs b/src/apps/cli/src/agent/runtime_client.rs index 78e471a7fc..d374f1a7ff 100644 --- a/src/apps/cli/src/agent/runtime_client.rs +++ b/src/apps/cli/src/agent/runtime_client.rs @@ -1820,6 +1820,29 @@ impl CliAgentRuntimeClient { submission } + pub(crate) async fn message_queue( + &self, + request: Option, + ) -> Result { + let session_id = self.require_session_id().await?; + let request = request.unwrap_or(openbitfun_runtime_ports::DialogQueueRequest { + session_id: session_id.clone(), + queue_epoch: None, + action: openbitfun_runtime_ports::DialogQueueAction::List, + }); + anyhow::ensure!( + request.session_id == session_id, + "Queue session changed; reopen /queue" + ); + match &self.backend { + CliAgentRuntimeBackend::Embedded(runtime) => runtime.manage_dialog_queue(request) + .await.map_err(|error| anyhow::anyhow!(error.into_message())), + CliAgentRuntimeBackend::Shared(_) => anyhow::bail!( + "This Shared Runtime does not expose message queue management. Use the execution host's queue controls." + ), + } + } + pub(crate) async fn steer_current_turn( &self, content: String, diff --git a/src/apps/cli/src/modes/chat.rs b/src/apps/cli/src/modes/chat.rs index 62f0a0bb37..2721638abe 100644 --- a/src/apps/cli/src/modes/chat.rs +++ b/src/apps/cli/src/modes/chat.rs @@ -1,4 +1,5 @@ mod external_editor; +mod message_queue; mod prompt_stash; /// Chat mode implementation /// @@ -347,6 +348,13 @@ struct PendingWorkspaceReferenceSearch { tokio::task::JoinHandle>, } +struct PendingMessageQueue { + generation: u64, + handle: tokio::task::JoinHandle< + std::result::Result, + >, +} + struct PendingWorkspaceDiff { handle: tokio::task::JoinHandle>, } @@ -512,6 +520,8 @@ pub(crate) struct ChatMode { /// the Runtime owner updates or deletes Session state. pending_session_operation: Option, pending_workspace_diff: Option, + pending_message_queue: Option, + next_message_queue_refresh: Instant, pending_local_effect: Option, pending_workspace_reference_search: Option, /// One lineage read in flight. Runtime I/O never blocks the TUI @@ -598,6 +608,8 @@ impl ChatMode { pending_mcp_tasks: Vec::new(), pending_session_operation: None, pending_workspace_diff: None, + pending_message_queue: None, + next_message_queue_refresh: Instant::now(), pending_local_effect: None, pending_workspace_reference_search: None, pending_lineage_operation: None, diff --git a/src/apps/cli/src/modes/chat/account.rs b/src/apps/cli/src/modes/chat/account.rs index 1d5a29fb0d..d57146b241 100644 --- a/src/apps/cli/src/modes/chat/account.rs +++ b/src/apps/cli/src/modes/chat/account.rs @@ -139,6 +139,7 @@ impl ChatMode { || chat_view.fork_selector_visible() || chat_view.timeline_selector_visible() || chat_view.prompt_stash_selector_visible() + || chat_view.message_queue_visible() || chat_view.export_dialog_visible() || chat_view.skill_selector_visible() || chat_view.subagent_selector_visible() @@ -167,6 +168,7 @@ impl ChatMode { chat_view.hide_fork_selector(); chat_view.hide_timeline_selector(); chat_view.hide_prompt_stash_selector(); + chat_view.hide_message_queue(); chat_view.hide_export_dialog(); chat_view.hide_skill_selector(); chat_view.hide_subagent_selector(); @@ -198,6 +200,7 @@ impl ChatMode { } crate::ui::chat::PopupType::ForkSelector => chat_view.hide_fork_selector(), crate::ui::chat::PopupType::TimelineSelector => chat_view.hide_timeline_selector(), + crate::ui::chat::PopupType::MessageQueue => chat_view.hide_message_queue(), crate::ui::chat::PopupType::PromptStashSelector => { chat_view.hide_prompt_stash_selector() } @@ -235,6 +238,7 @@ impl ChatMode { crate::ui::chat::PopupType::TimelineSelector => { chat_view.reshow_timeline_selector() } + crate::ui::chat::PopupType::MessageQueue => chat_view.reshow_message_queue(), crate::ui::chat::PopupType::PromptStashSelector => { chat_view.reshow_prompt_stash_selector() } diff --git a/src/apps/cli/src/modes/chat/commands.rs b/src/apps/cli/src/modes/chat/commands.rs index e2715f8a11..8e27d421e6 100644 --- a/src/apps/cli/src/modes/chat/commands.rs +++ b/src/apps/cli/src/modes/chat/commands.rs @@ -1189,6 +1189,14 @@ impl ChatMode { ActionHandler::PromptStash => self.stash_current_prompt(chat_view), ActionHandler::PromptStashPop => self.pop_prompt_stash(chat_view), ActionHandler::PromptStashList => self.show_prompt_stash(chat_view), + ActionHandler::MessageQueue => { + if self.pending_message_queue.is_some() { + chat_view.set_status(Some("A queue request is still pending".into())); + return Ok(None); + } + chat_view.show_message_queue(); + self.refresh_message_queue(chat_view, rt_handle, None); + } ActionHandler::ToggleTimestamps => { let visible = chat_view.toggle_timestamps(); self.persist_presentation_preference( diff --git a/src/apps/cli/src/modes/chat/input.rs b/src/apps/cli/src/modes/chat/input.rs index 5340f6db1e..b18ce24218 100644 --- a/src/apps/cli/src/modes/chat/input.rs +++ b/src/apps/cli/src/modes/chat/input.rs @@ -346,6 +346,20 @@ impl ChatMode { return Ok(None); } + if chat_view.message_queue_visible() { + match chat_view.message_queue_handle_key(key) { + crate::ui::message_queue::QueueAction::Close => self.navigate_back(chat_view), + crate::ui::message_queue::QueueAction::Refresh => { + self.refresh_message_queue(chat_view, rt_handle, None) + } + crate::ui::message_queue::QueueAction::Request(request) => { + self.refresh_message_queue(chat_view, rt_handle, Some(request)) + } + crate::ui::message_queue::QueueAction::None => {} + } + return Ok(None); + } + if chat_view.prompt_stash_selector_visible() { match chat_view.prompt_stash_selector_handle_key(key) { PromptStashAction::Select(id) => { diff --git a/src/apps/cli/src/modes/chat/message_queue.rs b/src/apps/cli/src/modes/chat/message_queue.rs new file mode 100644 index 0000000000..9955598cf4 --- /dev/null +++ b/src/apps/cli/src/modes/chat/message_queue.rs @@ -0,0 +1,74 @@ +use super::{ChatMode, ChatView}; +use openbitfun_runtime_ports::DialogQueueRequest; +use std::time::{Duration, Instant}; + +impl ChatMode { + pub(super) fn refresh_message_queue( + &mut self, + view: &mut ChatView, + runtime: &tokio::runtime::Handle, + request: Option, + ) { + if self.pending_message_queue.is_some() { + return; + } + view.message_queue_loading(); + let generation = view.message_queue_generation(); + let agent = self.agent.clone(); + let handle = runtime.spawn(async move { + match tokio::time::timeout( + std::time::Duration::from_secs(15), + agent.message_queue(request), + ) + .await + { + Ok(result) => { + result.map_err(|error| format!("{error}. Refresh before trying again.")) + } + Err(_) => { + Err("Queue reply timed out; outcome unknown. Refresh before retrying.".into()) + } + } + }); + self.pending_message_queue = Some(super::PendingMessageQueue { generation, handle }); + } + pub(super) fn poll_message_queue( + &mut self, + view: &mut ChatView, + runtime: &tokio::runtime::Handle, + ) -> bool { + if self.pending_message_queue.is_none() + && view.message_queue_can_auto_refresh() + && Instant::now() >= self.next_message_queue_refresh + { + self.refresh_message_queue(view, runtime, None); + return true; + } + if !self + .pending_message_queue + .as_ref() + .is_some_and(|p| p.handle.is_finished()) + { + return false; + } + let pending = self + .pending_message_queue + .take() + .expect("finished task exists"); + let result = tokio::task::block_in_place(|| { + tokio::runtime::Handle::current().block_on(pending.handle) + }) + .unwrap_or_else(|_| Err("Queue request stopped; refresh before retrying.".into())); + self.next_message_queue_refresh = Instant::now() + Duration::from_secs(2); + if view.message_queue_visible() && view.message_queue_generation() == pending.generation { + view.update_message_queue(result); + return true; + } + // A popup may have been closed and reopened while the old call was pending. + // Its reply is fenced out; schedule a fresh read for the new generation. + if view.message_queue_visible() { + self.next_message_queue_refresh = Instant::now(); + } + false + } +} diff --git a/src/apps/cli/src/modes/chat/run.rs b/src/apps/cli/src/modes/chat/run.rs index e244b12cad..c17255b3bc 100644 --- a/src/apps/cli/src/modes/chat/run.rs +++ b/src/apps/cli/src/modes/chat/run.rs @@ -618,6 +618,9 @@ impl ChatMode { if self.poll_workspace_reference_search(&mut chat_view) { needs_redraw = true; } + if self.poll_message_queue(&mut chat_view, &rt_handle) { + needs_redraw = true; + } if self.poll_workspace_diff(&mut chat_view) { needs_redraw = true; } diff --git a/src/apps/cli/src/ui/chat/mouse.rs b/src/apps/cli/src/ui/chat/mouse.rs index ced62bdb16..96f8d3b54a 100644 --- a/src/apps/cli/src/ui/chat/mouse.rs +++ b/src/apps/cli/src/ui/chat/mouse.rs @@ -34,6 +34,7 @@ impl ChatView { if self.fork_selector.is_visible() || self.timeline_selector.is_visible() || self.prompt_stash_selector.is_visible() + || self.message_queue_visible() { // These conversation-point dialogs are keyboard-driven. Do not let mouse gestures // mutate the transcript hidden underneath them. diff --git a/src/apps/cli/src/ui/chat/popups.rs b/src/apps/cli/src/ui/chat/popups.rs index 2452b966bc..69e585a9bc 100644 --- a/src/apps/cli/src/ui/chat/popups.rs +++ b/src/apps/cli/src/ui/chat/popups.rs @@ -1,4 +1,40 @@ impl ChatView { + pub(crate) fn show_message_queue(&mut self) { + self.message_queue.show(); + self.popup_stack.push(PopupType::MessageQueue); + } + pub(crate) fn message_queue_generation(&self) -> u64 { + self.message_queue.generation + } + pub(crate) fn message_queue_can_auto_refresh(&self) -> bool { + self.message_queue.can_auto_refresh() + } + pub(crate) fn message_queue_loading(&mut self) { + self.message_queue.loading(); + } + pub(crate) fn message_queue_visible(&self) -> bool { + self.message_queue.visible + } + pub(crate) fn hide_message_queue(&mut self) { + self.message_queue.visible = false; + self.message_queue.generation = self.message_queue.generation.wrapping_add(1); + } + pub(crate) fn reshow_message_queue(&mut self) { + self.message_queue.visible = true; + } + pub(crate) fn update_message_queue( + &mut self, + result: Result, + ) { + self.message_queue.update(result); + } + pub(crate) fn message_queue_handle_key( + &mut self, + key: crossterm::event::KeyEvent, + ) -> super::message_queue::QueueAction { + self.message_queue.handle_key(key) + } + pub(crate) fn show_prompt_command_shell_review( &mut self, plan: openbitfun_product_domains::external_sources::PromptCommandShellReviewPlan, diff --git a/src/apps/cli/src/ui/chat/render.rs b/src/apps/cli/src/ui/chat/render.rs index cb590e0b08..7262068e37 100644 --- a/src/apps/cli/src/ui/chat/render.rs +++ b/src/apps/cli/src/ui/chat/render.rs @@ -111,6 +111,7 @@ impl ChatView { .render(frame, chunks[1], &self.theme); self.render_fork_selector(frame, chunks[1]); self.render_timeline_selector(frame, chunks[1]); + self.message_queue.render(frame, chunks[1], &self.theme); self.prompt_stash_selector .render(frame, chunks[1], &self.theme); self.export_dialog.render(frame, size, &self.theme); diff --git a/src/apps/cli/src/ui/chat/state.rs b/src/apps/cli/src/ui/chat/state.rs index 64563be59f..4ead5ad59f 100644 --- a/src/apps/cli/src/ui/chat/state.rs +++ b/src/apps/cli/src/ui/chat/state.rs @@ -81,6 +81,7 @@ pub(crate) enum PopupType { ForkSelector, TimelineSelector, PromptStashSelector, + MessageQueue, ExportDialog, SkillSelector, SubagentSelector, @@ -250,6 +251,7 @@ pub(crate) struct ChatView { timeline_selector: TimelineSelectorState, lineage_inspection_label: Option, prompt_stash_selector: PromptStashSelectorState, + message_queue: super::message_queue::MessageQueueState, export_dialog: ExportDialogState, /// Skill selector popup state skill_selector: SkillSelectorState, @@ -382,6 +384,7 @@ impl ChatView { timeline_selector: TimelineSelectorState::new(), lineage_inspection_label: None, prompt_stash_selector: PromptStashSelectorState::new(), + message_queue: super::message_queue::MessageQueueState::new(), export_dialog: ExportDialogState::new(), skill_selector: SkillSelectorState::new(), subagent_selector: SubagentSelectorState::new(), diff --git a/src/apps/cli/src/ui/command_palette.rs b/src/apps/cli/src/ui/command_palette.rs index 398b228e15..ab5d8c5932 100644 --- a/src/apps/cli/src/ui/command_palette.rs +++ b/src/apps/cli/src/ui/command_palette.rs @@ -56,6 +56,7 @@ const DEFAULT_ITEM_ORDER: &[&str] = &[ "prompt_stash", "prompt_stash_pop", "prompt_stash_list", + "message_queue", "copy_transcript", "export_transcript", "toggle_auto_approve", diff --git a/src/apps/cli/src/ui/message_queue.rs b/src/apps/cli/src/ui/message_queue.rs new file mode 100644 index 0000000000..b96ce7da46 --- /dev/null +++ b/src/apps/cli/src/ui/message_queue.rs @@ -0,0 +1,359 @@ +//! Keyboard presentation of the execution host's queue; no local scheduling. +use crate::ui::theme::{StyleKind, Theme}; +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use openbitfun_runtime_ports::{ + DialogQueueAction, DialogQueueRequest, DialogQueueSnapshot, DialogQueueStatus, +}; +use ratatui::{ + layout::Rect, + style::Style, + text::{Line, Span}, + widgets::{Clear, List, ListItem, ListState, Paragraph, Wrap}, + Frame, +}; + +pub(crate) enum QueueAction { + None, + Close, + Refresh, + Request(DialogQueueRequest), +} + +pub(super) struct MessageQueueState { + pub(super) visible: bool, + pub(super) generation: u64, + snapshot: Option, + list: ListState, + error: Option, + busy: bool, +} +impl MessageQueueState { + pub(super) fn new() -> Self { + Self { + generation: 0, + visible: false, + snapshot: None, + list: ListState::default(), + error: None, + busy: false, + } + } + pub(super) fn show(&mut self) { + let generation = self.generation.wrapping_add(1); + *self = Self::new(); + self.generation = generation; + self.visible = true; + } + pub(super) fn can_auto_refresh(&self) -> bool { + self.visible && !self.busy && self.error.is_none() + } + pub(super) fn loading(&mut self) { + self.busy = true; + } + pub(super) fn update(&mut self, result: Result) { + self.busy = false; + match result { + Ok(snapshot) => { + let selected = self + .snapshot + .as_ref() + .and_then(|s| s.items.get(self.list.selected()?)) + .map(|i| i.turn_id.clone()); + let next = selected + .and_then(|id| snapshot.items.iter().position(|i| i.turn_id == id)) + .unwrap_or(0); + self.list + .select((!snapshot.items.is_empty()).then_some(next)); + self.snapshot = Some(snapshot); + self.error = None; + } + Err(error) => self.error = Some(error), + } + } + pub(super) fn handle_key(&mut self, key: KeyEvent) -> QueueAction { + if key.code == KeyCode::Esc { + return QueueAction::Close; + } + if self.busy { + return QueueAction::None; + } + if key.code == KeyCode::Char('r') { + return QueueAction::Refresh; + } + let Some(snapshot) = self.snapshot.as_ref() else { + return QueueAction::None; + }; + let Some(index) = self.list.selected().filter(|i| *i < snapshot.items.len()) else { + return QueueAction::None; + }; + let item = &snapshot.items[index]; + let delta = match key.code { + KeyCode::Up => -1, + KeyCode::Down => 1, + _ => 0, + }; + if delta != 0 && !key.modifiers.contains(KeyModifiers::SHIFT) { + self.list.select(Some( + (index as isize + delta).clamp(0, snapshot.items.len() as isize - 1) as usize, + )); + return QueueAction::None; + } + if self.error.is_some() + || !matches!( + item.status, + DialogQueueStatus::Queued | DialogQueueStatus::Blocked + ) + { + return QueueAction::None; + } + let operation_id = uuid::Uuid::new_v4().to_string(); + let action = if delta != 0 { + if snapshot.supports_reorder != Some(true) || item.status != DialogQueueStatus::Queued { + return QueueAction::None; + } + let movable: Vec<_> = snapshot + .items + .iter() + .filter(|i| i.status == DialogQueueStatus::Queued) + .collect(); + let position = movable + .iter() + .position(|i| i.turn_id == item.turn_id) + .unwrap(); + if (delta < 0 && position == 0) || (delta > 0 && position + 1 == movable.len()) { + return QueueAction::None; + } + DialogQueueAction::Reorder { + turn_id: item.turn_id.clone(), + before_turn_id: if delta < 0 { + Some(movable[position - 1].turn_id.clone()) + } else { + movable.get(position + 2).map(|i| i.turn_id.clone()) + }, + operation_id, + expected_revision: snapshot.revision, + } + } else { + match key.code { + KeyCode::Enter => DialogQueueAction::Promote { + turn_id: item.turn_id.clone(), + operation_id, + expected_active_turn_id: snapshot.active_turn_id.clone(), + }, + KeyCode::Delete => DialogQueueAction::Cancel { + turn_id: item.turn_id.clone(), + operation_id, + }, + _ => return QueueAction::None, + } + }; + QueueAction::Request(DialogQueueRequest { + session_id: snapshot.session_id.clone(), + queue_epoch: Some(snapshot.queue_epoch.clone()), + action, + }) + } + pub(super) fn render(&mut self, frame: &mut Frame, area: Rect, theme: &Theme) { + if !self.visible { + return; + } + if area.width < 40 || area.height < 10 { + frame.render_widget(Clear, area); + frame.render_widget( + Paragraph::new("Enlarge terminal to view the queue. Esc closes.") + .style(theme.style(StyleKind::Muted)) + .wrap(Wrap { trim: true }), + area, + ); + return; + } + let width = area.width.saturating_sub(4).min(88); + let count = self.snapshot.as_ref().map_or(0, |s| s.items.len()); + let height = (count as u16 * 2 + 6).max(8).min(area.height); + let popup = Rect::new( + area.x + (area.width - width) / 2, + area.y + (area.height - height) / 2, + width, + height, + ); + frame.render_widget(Clear, popup); + frame.render_widget( + Paragraph::new("").style(Style::default().bg(theme.background)), + popup, + ); + let inner = Rect::new(popup.x + 2, popup.y, width - 4, height); + frame.render_widget( + Paragraph::new(format!( + "Queued messages · {count}{}", + if self.busy { " · Updating…" } else { "" } + )) + .style(theme.style(StyleKind::Primary)), + Rect { height: 1, ..inner }, + ); + let items = self + .snapshot + .as_ref() + .map(|s| { + s.items + .iter() + .enumerate() + .map(|(index, item)| { + let selected = self.list.selected() == Some(index); + let preview = item + .display_content + .split_whitespace() + .collect::>() + .join(" "); + let suffix = if item.attachment_count > 0 { + format!(" +{} attachments", item.attachment_count) + } else { + String::new() + }; + let status = if item.status == DialogQueueStatus::Queued { + "" + } else { + " [waiting]" + }; + ListItem::new(vec![ + Line::from(Span::styled( + format!(" {}", "─".repeat(inner.width.saturating_sub(2) as usize)), + theme.style(StyleKind::Muted), + )), + Line::from(vec![ + Span::raw(if selected { "› " } else { " " }), + Span::raw(preview), + Span::styled( + format!("{suffix}{status}"), + if selected { + Style::default() + } else { + theme.style(StyleKind::Muted) + }, + ), + ]) + .style(if selected { + Style::default() + .bg(theme.primary) + .fg(theme.selection_foreground()) + } else { + Style::default() + }), + ]) + }) + .collect::>() + }) + .unwrap_or_default(); + frame.render_stateful_widget( + List::new(items), + Rect::new(inner.x, inner.y + 2, inner.width, height.saturating_sub(6)), + &mut self.list, + ); + let notice = self.error.as_deref().unwrap_or_else(|| { + if self + .snapshot + .as_ref() + .is_some_and(|s| s.supports_reorder != Some(true)) + { + "Reordering requires an updated execution host." + } else if count == 0 { + "No queued messages" + } else { + "Order is confirmed by the execution host." + } + }); + frame.render_widget( + Paragraph::new(notice) + .style(theme.style(StyleKind::Muted)) + .wrap(Wrap { trim: true }), + Rect::new(inner.x, inner.y + height - 4, inner.width, 2), + ); + frame.render_widget( + Paragraph::new("↑↓ Select ⇧↑↓ Move ↵ Send now\nDel Remove r Refresh Esc Close") + .style(theme.style(StyleKind::Muted)), + Rect::new(inner.x, inner.y + height - 2, inner.width, 2), + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn state() -> MessageQueueState { + let mut state = MessageQueueState::new(); + state.show(); + state.update(Ok(serde_json::from_value(serde_json::json!({"sessionId":"s","queueEpoch":"e","revision":7,"activeTurnId":"active","supportsReorder":true,"capacity":10,"used":2,"receipt":null,"items":[ + {"turnId":"a","displayContent":"First","previewTruncated":false,"attachmentCount":1,"agentType":"Standard","createdAtMs":0,"status":"queued","reason":null,"targetTurnId":null,"steeringId":null}, + {"turnId":"b","displayContent":"Second","previewTruncated":false,"attachmentCount":0,"agentType":"Standard","createdAtMs":0,"status":"queued","reason":null,"targetTurnId":null,"steeringId":null} + ]})).unwrap())); + state + } + #[test] + fn message_queue_moves_use_observed_revision_and_keep_order_until_receipt() { + let mut state = state(); + let QueueAction::Request(request) = + state.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::SHIFT)) + else { + panic!("move"); + }; + assert_eq!(request.queue_epoch.as_deref(), Some("e")); + assert!( + matches!(request.action, DialogQueueAction::Reorder { ref turn_id, before_turn_id: None, expected_revision: 7, .. } if turn_id == "a") + ); + assert_eq!(state.snapshot.unwrap().items[0].turn_id, "a"); + } + #[test] + fn message_queue_render_keeps_inset_separators_and_keyboard_help() { + for width in [40, 80] { + let mut state = state(); + let backend = ratatui::backend::TestBackend::new(width, 18); + let mut terminal = ratatui::Terminal::new(backend).unwrap(); + terminal + .draw(|frame| state.render(frame, frame.area(), &Theme::dark())) + .unwrap(); + let buffer = terminal.backend().buffer(); + let rows: Vec = (0..18) + .map(|y| (0..width).map(|x| buffer[(x, y)].symbol()).collect()) + .collect(); + let first = rows.iter().position(|r| r.contains("First")).unwrap(); + let second = rows.iter().position(|r| r.contains("Second")).unwrap(); + assert!(rows[first].contains("› First")); + let attachment_column = rows[first].chars().position(|c| c == '+').unwrap() as u16; + assert_eq!( + buffer[(attachment_column, first as u16)].fg, + Theme::dark().selection_foreground() + ); + assert!(rows[first - 1].contains('─')); + assert!(rows[second - 1].contains('─')); + assert!(!rows[second + 1].contains('─')); + assert!(rows.iter().any(|r| r.contains("⇧↑↓ Move"))); + assert!(rows.iter().any(|r| r.contains("Esc Close"))); + if width == 80 { + println!( + "QUEUE_PREVIEW_BEGIN\n{}\nQUEUE_PREVIEW_END", + rows.join("\n") + ); + } + } + } + #[test] + fn message_queue_errors_require_refresh_and_legacy_hosts_cannot_move() { + let mut state = state(); + assert!(state.can_auto_refresh()); + state.update(Err("Outcome unknown; refresh before retrying".into())); + assert!(!state.can_auto_refresh()); + assert!(matches!( + state.handle_key(KeyEvent::new(KeyCode::Delete, KeyModifiers::NONE)), + QueueAction::None + )); + assert!(matches!( + state.handle_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE)), + QueueAction::Refresh + )); + state.error = None; + state.snapshot.as_mut().unwrap().supports_reorder = None; + assert!(matches!( + state.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::SHIFT)), + QueueAction::None + )); + } +} diff --git a/src/apps/cli/src/ui/mod.rs b/src/apps/cli/src/ui/mod.rs index 0d63333b4e..2c26509ca0 100644 --- a/src/apps/cli/src/ui/mod.rs +++ b/src/apps/cli/src/ui/mod.rs @@ -16,6 +16,7 @@ pub(crate) mod login_form; mod markdown; pub(crate) mod mcp_add_dialog; pub(crate) mod mcp_selector; +pub(crate) mod message_queue; mod message_time; pub(crate) mod model_config_form; pub(crate) mod model_selector; diff --git a/src/apps/cli/src/ui/startup.rs b/src/apps/cli/src/ui/startup.rs index aaf5de7b70..afd0b3abd6 100644 --- a/src/apps/cli/src/ui/startup.rs +++ b/src/apps/cli/src/ui/startup.rs @@ -1114,6 +1114,7 @@ impl StartupPage { | ActionHandler::PromptStash | ActionHandler::PromptStashPop | ActionHandler::PromptStashList + | ActionHandler::MessageQueue | ActionHandler::ToggleTimestamps | ActionHandler::ToggleThinking | ActionHandler::ToggleToolDetails diff --git a/src/apps/miniapp-shell/src/generated/chat-styles.css b/src/apps/miniapp-shell/src/generated/chat-styles.css index 4578a846af..cc251a1a3b 100644 --- a/src/apps/miniapp-shell/src/generated/chat-styles.css +++ b/src/apps/miniapp-shell/src/generated/chat-styles.css @@ -347,6 +347,10 @@ gap: var(--openbitfun-space-2); } + .miniapp-ChatComposer-body:has(> .miniapp-ChatComposer-queue > [data-openbitfun-component="chat-composer-queue"]) { + gap: 0; + } + .miniapp-ChatComposer-queue { /* The wrapper exists when a queue component later renders `null`. Keeping it out of the box tree makes both that transition and the no-queue path diff --git a/src/apps/mobile/AGENTS.md b/src/apps/mobile/AGENTS.md index 686ac4c127..e166e796af 100644 --- a/src/apps/mobile/AGENTS.md +++ b/src/apps/mobile/AGENTS.md @@ -123,3 +123,14 @@ its existing native host and invokes the same generator without native wrappers. Run `node --test src/apps/mobile/miniapps/*.test.cjs src/apps/mobile/harmonyos/miniapps/*.test.cjs` from the repository root after bundle/bridge changes. Storage keys remain scoped to an allowlisted app; retain unreadable records and surface the error. + +For host-queue negotiation, stale replies, disconnect retention and mutation +conflicts, run from `shared/`: + +```bash +./gradlew :core-feature:jvmTest --tests '*MessageQueueStoreTest*' +``` + +These simulated-host tests do not establish live Relay, SSH, Peer Device or +Detached Dispatch behavior. Queue ordering belongs to the execution host; +native views submit intents and never optimistically replace its order. diff --git a/src/apps/mobile/README.md b/src/apps/mobile/README.md index 3c0859aaa0..b7036f3730 100644 --- a/src/apps/mobile/README.md +++ b/src/apps/mobile/README.md @@ -68,6 +68,7 @@ metadata, execution-mode IDs, speech draft merging, and completion observation i |---|---|---| | Execution modes | Minimal / Standard / Ultimate, with the HarmonyOS density glyph; workspace menus also retain Cowork | Enabled only by live `get_workspace_info.capabilities` containing `harness_profiles_v1`; older hosts keep Code / Cowork. Capability absence in old payloads is covered by a round-trip test. | | Running-turn input | A nonempty remote draft offers Send; an empty composer retains Stop | Hosts advertising `dialog_steer_v1` receive `steer_turn` with the active turn ID. Older hosts retain `send_message` queueing; failed sends retain the draft and attachments. | +| Pending messages | Android, iOS and HarmonyOS show the execution host’s queue above the composer. Drag the handle, or use Move up/down in the menu; Send now and Remove affect only the selected message. | Requires `dialog_queue_v1`; reordering additionally requires `supportsReorder` in the snapshot. Older hosts retain their working controls and show why sorting is unavailable. Offline or failed replies retain the list, and changing sessions cancels stale gestures and replies. | | Next-input suggestions | Android, iOS and HarmonyOS show the host's suggestion above an empty, idle composer; tapping fills and focuses the editor without sending | Uses the existing host session stream. Hints retain their exact text and retire on newer turns, session changes or host restarts. Older hosts simply show no hint; no new Relay API or migration is needed. | | Plans | Legacy CreatePlan, structured plans and `.plan.md` writes show a plan card with file preview and Build | Build requires `plan_build_v1`, a completed plan tool and an idle connected session. Paths remain remote; the mobile app never runs the plan locally. | | Offline Mini Apps | Gomoku, Regex Playground and Daily Divination open from welcome and sidebar without login | Product-owned sources are bundled by `miniapps/generate.cjs`; native WebView hosts expose only per-app allowlisted storage and clipboard. No network, Node or shell bridge. | diff --git a/src/apps/mobile/android/AGENTS.md b/src/apps/mobile/android/AGENTS.md index 5b5ba284ed..efd72c7a4d 100644 --- a/src/apps/mobile/android/AGENTS.md +++ b/src/apps/mobile/android/AGENTS.md @@ -68,3 +68,13 @@ Run instrumented Gradle tests on a dedicated test emulator, not an authenticated manual-acceptance device. The test runner can uninstall the target application after the suite and remove its local account state. Use `adb install -r` for manual acceptance updates to preserve that state. + +For queue menus, touch targets, drag completion and cancellation on host revision: + +```bash +./gradlew :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.openbitfun.mobile.app.MessageQueuePanelTest +``` + +The isolated `message-queue` design-preview scenario uses the production panel +with simulated host replies. Review compact/wide widths and light/dark themes; +this does not establish live remote dispatch behavior. diff --git a/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MessageQueuePanelTest.kt b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MessageQueuePanelTest.kt new file mode 100644 index 0000000000..d5a6852557 --- /dev/null +++ b/src/apps/mobile/android/app/src/androidTest/kotlin/com/openbitfun/mobile/app/MessageQueuePanelTest.kt @@ -0,0 +1,68 @@ +package com.openbitfun.mobile.app + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.test.* +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.unit.dp +import androidx.test.platform.app.InstrumentationRegistry +import com.openbitfun.mobile.app.ui.chat.MessageQueuePanel +import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme +import com.openbitfun.mobile.core.feature.session.* +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test + +class MessageQueuePanelTest { + @get:Rule val rule = createComposeRule() + private val context get() = InstrumentationRegistry.getInstrumentation().targetContext + private fun state(supports: Boolean = true) = MessageQueueUiState("s", true, supports, "e:1", listOf( + QueuedMessageUiState("a", "First", 1, "queued", null), + QueuedMessageUiState("b", "Second", 0, "queued", null), + QueuedMessageUiState("c", "Third", 0, "queued", null), + ), false, null) + + @Test fun compactMenuMovesUseStableMessageIdentityInBothThemes() { + var dark by mutableStateOf(true) + val intents = mutableListOf() + rule.setContent { OpenBitFunTheme(dark = dark) { Box(Modifier.width(320.dp)) { MessageQueuePanel(state(), intents::add) } } } + repeat(2) { + rule.onAllNodesWithContentDescription(context.getString(R.string.queue_more))[0].performClick() + rule.onNodeWithText(context.getString(R.string.queue_move_up)).assertIsNotEnabled() + rule.onNodeWithText(context.getString(R.string.queue_move_down)).performClick() + assertEquals(RemoteSessionIntent.MoveQueuedMessage("a", "c"), intents.last()) + rule.runOnIdle { dark = false } + } + } + + @Test fun longPressDragCommitsOnceAtRelease() { + val intents = mutableListOf() + rule.setContent { OpenBitFunTheme(dark = true) { Box(Modifier.width(320.dp)) { MessageQueuePanel(state(), intents::add) } } } + val handles = rule.onAllNodesWithContentDescription(context.getString(R.string.queue_reorder)) + val offset = handles[0].fetchSemanticsNode().boundsInRoot.center.y - handles[2].fetchSemanticsNode().boundsInRoot.center.y - 10f + handles[2].performTouchInput { + down(center); advanceEventTime(650); moveBy(Offset(0f, offset), delayMillis = 120) + } + rule.runOnIdle { assertTrue(intents.isEmpty()) } + handles[2].performTouchInput { up() } + rule.runOnIdle { assertEquals(listOf(RemoteSessionIntent.MoveQueuedMessage("c", "a")), intents) } + } + + @Test fun hostRevisionChangeCancelsAnActiveDragAndLegacyHostsHaveNoHandle() { + var current by mutableStateOf(state()) + val intents = mutableListOf() + rule.setContent { OpenBitFunTheme(dark = false) { MessageQueuePanel(current, intents::add) } } + val handles = rule.onAllNodesWithContentDescription(context.getString(R.string.queue_reorder)) + handles[0].performTouchInput { down(center); advanceEventTime(650); moveBy(Offset(0f, 100f), delayMillis = 120) } + rule.runOnIdle { current = current.copy(revisionKey = "e:2") } + handles[0].performTouchInput { up() } + rule.runOnIdle { assertTrue(intents.isEmpty()); current = current.copy(supportsReorder = false) } + rule.onAllNodesWithContentDescription(context.getString(R.string.queue_reorder)).assertCountEquals(0) + rule.onAllNodesWithContentDescription(context.getString(R.string.queue_more))[0].performClick() + rule.onNodeWithText(context.getString(R.string.queue_unsupported)).assertExists() + rule.onNodeWithText(context.getString(R.string.queue_move_down)).assertIsNotEnabled() + } +} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/MainActivity.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/MainActivity.kt index 67c091614e..feb0b1119c 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/MainActivity.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/MainActivity.kt @@ -35,6 +35,7 @@ import com.openbitfun.mobile.app.platform.LogcatCoreLog import com.openbitfun.mobile.app.ui.shell.MobileScreen import com.openbitfun.mobile.app.platform.StartupRevealPreference import com.openbitfun.mobile.app.platform.AppLocaleController +import com.openbitfun.mobile.app.ui.preview.MessageQueuePreview import com.openbitfun.mobile.app.ui.preview.MobileDesignGallery import com.openbitfun.mobile.app.ui.preview.mobileDesignScenario import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme @@ -63,6 +64,10 @@ class MainActivity : ComponentActivity() { if (android.os.Build.VERSION.SDK_INT >= 29) window.isNavigationBarContrastEnforced = false setContent { if (intent.getBooleanExtra(DESIGN_PREVIEW_EXTRA, false)) { + if (intent.getStringExtra(DESIGN_SCENARIO_EXTRA) == "message-queue") { + MessageQueuePreview() + return@setContent + } val scenario = mobileDesignScenario(intent.getStringExtra(DESIGN_SCENARIO_EXTRA)) MobileDesignGallery(scenario = scenario, dark = scenario.appearance == "dark") return@setContent diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerBar.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerBar.kt index 0eac37e2d8..e4020c7513 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerBar.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ComposerBar.kt @@ -153,6 +153,7 @@ internal fun ComposerBar( placeholder: String, onDraftChange: (String) -> Unit, promptSuggestion: String? = null, + queueAttached: Boolean = false, onRemoveImage: (String) -> Unit, onAttach: () -> Unit, onVoice: () -> Unit, @@ -232,7 +233,7 @@ internal fun ComposerBar( .padding( start = MobileDesignGeometry.ConversationOverlaySideInset, end = MobileDesignGeometry.ConversationOverlaySideInset, - top = 8.dp, + top = if (queueAttached) 0.dp else 8.dp, bottom = 14.dp, ) .testTag(COMPOSER_TEST_TAG), diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationView.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationView.kt index 70b338cdad..943914c348 100644 --- a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationView.kt +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/ConversationView.kt @@ -354,7 +354,10 @@ internal fun ConversationView( Text(stringResource(R.string.chat_attachment_recovery_failed)) } } + val queueMatchesSession = state.messageQueue.sessionId == state.selectedSessionId + if (queueMatchesSession) MessageQueuePanel(state.messageQueue, onIntent) ComposerBar( + queueAttached = queueMatchesSession && (state.messageQueue.items.isNotEmpty() || state.messageQueue.failure != null), draft = draft, images = images, // An empty session id would send nowhere, so it reads as busy. diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MessageQueuePanel.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MessageQueuePanel.kt new file mode 100644 index 0000000000..754e89f2e2 --- /dev/null +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/chat/MessageQueuePanel.kt @@ -0,0 +1,141 @@ +package com.openbitfun.mobile.app.ui.chat + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.zIndex +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.boundsInRoot +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.CustomAccessibilityAction +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.customActions +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.openbitfun.mobile.app.R +import com.openbitfun.mobile.app.ui.theme.openBitFunColors +import com.openbitfun.mobile.core.feature.session.MessageQueueFailure +import com.openbitfun.mobile.core.feature.session.MessageQueueUiState +import com.openbitfun.mobile.core.feature.session.RemoteSessionIntent + +/** Host receipts stay authoritative; a gesture submits one move only on release. */ +@Composable +internal fun MessageQueuePanel(state: MessageQueueUiState, onIntent: (RemoteSessionIntent) -> Unit) { + if (state.items.isEmpty() && state.failure == null) return + var expanded by remember(state.sessionId) { mutableStateOf(true) } + var menuId by remember(state.sessionId) { mutableStateOf(null) } + var dragging by remember(state.sessionId) { mutableStateOf(null) } + var displacement by remember { mutableFloatStateOf(0f) } + var destination by remember { mutableStateOf(null) } + var dragBounds by remember { mutableStateOf>(emptyMap()) } + val bounds = remember { mutableMapOf() } + val queued = state.items.filter { it.status == "queued" }.map { it.id } + val enabled = state.supportsReorder && !state.busy && state.failure == null + val latestIntent by rememberUpdatedState(onIntent) + val moveUp = stringResource(R.string.queue_move_up) + val moveDown = stringResource(R.string.queue_move_down) + val handleLabel = stringResource(R.string.queue_reorder) + LaunchedEffect(state.revisionKey, state.busy, state.failure) { dragging = null; displacement = 0f } + Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp)) { + TextButton(onClick = { expanded = !expanded }, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurfaceVariant), contentPadding = PaddingValues(horizontal = 8.dp)) { + Text(stringResource(R.string.queue_title, state.items.size), style = MaterialTheme.typography.labelMedium) + Icon(painterResource(if (expanded) R.drawable.ic_symbol_chevron_down else R.drawable.ic_symbol_chevron_up), null, Modifier.size(14.dp)) + } + if (state.failure != null) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(if (state.failure == MessageQueueFailure.UNSUPPORTED) R.string.queue_unsupported else R.string.queue_refresh_required), Modifier.weight(1f), style = MaterialTheme.typography.bodySmall) + TextButton(onClick = { onIntent(RemoteSessionIntent.RefreshMessageQueue) }, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), enabled = !state.busy) { Text(stringResource(R.string.queue_refresh)) } + } + } + if (expanded) Column(Modifier.heightIn(max = 192.dp).verticalScroll(rememberScrollState())) { + state.items.forEach { item -> + key(item.id) { + val index = queued.indexOf(item.id) + val canMove = enabled && index >= 0 && queued.size > 1 + val ink = MaterialTheme.colorScheme.onSurfaceVariant + val marker = MaterialTheme.colorScheme.primary + Column(Modifier.onGloballyPositioned { bounds[item.id] = it.boundsInRoot() } + .graphicsLayer { if (dragging == item.id) translationY = displacement } + .zIndex(if (dragging == item.id) 1f else 0f) + .background(if (dragging == item.id) MaterialTheme.colorScheme.surfaceContainer else openBitFunColors.transparent) + .drawWithContent { + drawContent() + if (dragging != null && dragging != item.id) { + val y = if (destination == item.id) 0f + else if (destination == null && item.id == queued.lastOrNull { it != dragging }) size.height + else null + if (y != null) drawLine(marker, Offset(0f, y), Offset(size.width, y), 1.dp.toPx()) + } + } + .semantics { + customActions = if (canMove) listOfNotNull( + if (index > 0) CustomAccessibilityAction(moveUp) { onIntent(RemoteSessionIntent.MoveQueuedMessage(item.id, queued[index - 1])); true } else null, + if (index < queued.lastIndex) CustomAccessibilityAction(moveDown) { onIntent(RemoteSessionIntent.MoveQueuedMessage(item.id, queued.getOrNull(index + 2))); true } else null, + ) else emptyList() + }) { + HorizontalDivider(Modifier.padding(horizontal = 8.dp), color = MaterialTheme.colorScheme.outlineVariant) + Row(Modifier.fillMaxWidth().heightIn(min = 48.dp), verticalAlignment = Alignment.Top) { + if (state.supportsReorder) IconButton(onClick = { menuId = item.id }, enabled = canMove, + modifier = Modifier.size(width = 48.dp, height = 48.dp).pointerInput(item.id, queued, enabled, state.revisionKey) { + if (canMove) detectDragGesturesAfterLongPress( + onDragStart = { dragBounds = bounds.toMap(); dragging = item.id; displacement = 0f; destination = queued.getOrNull(index + 1) }, + onDragCancel = { dragging = null; displacement = 0f }, + onDragEnd = { + if (dragging == item.id && destination != queued.getOrNull(index + 1)) latestIntent(RemoteSessionIntent.MoveQueuedMessage(item.id, destination)) + dragging = null; displacement = 0f + }, + onDrag = { change, amount -> + change.consume(); displacement += amount.y + val center = (dragBounds[item.id]?.center?.y ?: 0f) + displacement + destination = queued.firstOrNull { it != item.id && center < (dragBounds[it]?.center?.y ?: Float.MAX_VALUE) } + }, + ) + }) { + Canvas(Modifier.size(14.dp).semantics { contentDescription = handleLabel }) { + for (line in 1..3) drawLine(ink, Offset(1f, size.height * line / 4), Offset(size.width - 1f, size.height * line / 4), strokeWidth = 1.5.dp.toPx()) + } + } + Column(Modifier.weight(1f).padding(vertical = 14.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Text(item.text, Modifier.weight(1f, fill = false), maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium) + if (item.attachmentCount > 0) Text(stringResource(R.string.queue_attachments, item.attachmentCount), style = MaterialTheme.typography.labelSmall, color = ink) + } + if (item.status != "queued") Text(stringResource(R.string.queue_waiting), style = MaterialTheme.typography.bodySmall, color = ink) + } + IconButton(onClick = { onIntent(RemoteSessionIntent.PromoteQueuedMessage(item.id)) }, enabled = !state.busy && state.failure == null && item.status in listOf("queued", "blocked")) { + Icon(painterResource(R.drawable.ic_symbol_arrow_up), stringResource(R.string.queue_send_now), Modifier.size(16.dp)) + } + Box { + IconButton(onClick = { menuId = item.id }) { Icon(painterResource(R.drawable.ic_symbol_ellipsis), stringResource(R.string.queue_more), Modifier.size(16.dp)) } + DropdownMenu(expanded = menuId == item.id, onDismissRequest = { menuId = null }) { + DropdownMenuItem(text = { Text(item.text) }, onClick = {}, enabled = false) + if (!state.supportsReorder) DropdownMenuItem(text = { Text(stringResource(R.string.queue_unsupported)) }, onClick = {}, enabled = false) + DropdownMenuItem(text = { Text(moveUp) }, enabled = canMove && index > 0, + onClick = { menuId = null; onIntent(RemoteSessionIntent.MoveQueuedMessage(item.id, queued[index - 1])) }) + DropdownMenuItem(text = { Text(moveDown) }, enabled = canMove && index < queued.lastIndex, + onClick = { menuId = null; onIntent(RemoteSessionIntent.MoveQueuedMessage(item.id, queued.getOrNull(index + 2))) }) + DropdownMenuItem(text = { Text(stringResource(R.string.queue_remove)) }, enabled = !state.busy && state.failure == null && item.status in listOf("queued", "blocked"), + onClick = { menuId = null; onIntent(RemoteSessionIntent.CancelQueuedMessage(item.id)) }) + } + } + } + } + } + } + } + } +} diff --git a/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MessageQueuePreview.kt b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MessageQueuePreview.kt new file mode 100644 index 0000000000..3dd686f8d8 --- /dev/null +++ b/src/apps/mobile/android/app/src/main/kotlin/com/openbitfun/mobile/app/ui/preview/MessageQueuePreview.kt @@ -0,0 +1,54 @@ +package com.openbitfun.mobile.app.ui.preview + +import androidx.compose.foundation.layout.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.openbitfun.mobile.app.ui.chat.MessageQueuePanel +import com.openbitfun.mobile.app.ui.theme.OpenBitFunTheme +import com.openbitfun.mobile.core.feature.session.* + +/** Isolated native review surface. The production panel uses simulated host replies. */ +@Composable +internal fun MessageQueuePreview() { + var dark by remember { mutableStateOf(true) } + var narrow by remember { mutableStateOf(true) } + var revision by remember { mutableIntStateOf(1) } + var items by remember { mutableStateOf(listOf( + QueuedMessageUiState("first", "Review the queue layout", 1, "queued", null), + QueuedMessageUiState("second", "Check long messages and attachment spacing", 2, "queued", null), + QueuedMessageUiState("third", "Run the focused tests", 0, "queued", null), + )) } + OpenBitFunTheme(dark = dark) { + Surface(Modifier.fillMaxSize()) { + Column(Modifier.fillMaxSize().safeDrawingPadding(), verticalArrangement = Arrangement.Center) { + Row(Modifier.padding(horizontal = 12.dp)) { + TextButton(onClick = { dark = !dark }, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurfaceVariant)) { Text("Light / Dark") } + TextButton(onClick = { narrow = !narrow }, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurfaceVariant)) { Text("Resize") } + } + Text("Queue · Native component preview", Modifier.padding(20.dp), style = MaterialTheme.typography.titleMedium) + Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { + Box(if (narrow) Modifier.width(320.dp) else Modifier.fillMaxWidth()) { + MessageQueuePanel(MessageQueueUiState("preview", true, true, "preview:$revision", items, false, null)) { intent -> + when (intent) { + is RemoteSessionIntent.MoveQueuedMessage -> { + val item = items.firstOrNull { it.id == intent.id } + if (item != null) { + val next = items.filterNot { it.id == intent.id }.toMutableList() + next.add(intent.beforeId?.let { id -> next.indexOfFirst { it.id == id } }?.coerceAtLeast(0) ?: next.size, item) + items = next; revision++ + } + } + is RemoteSessionIntent.CancelQueuedMessage -> { items = items.filterNot { it.id == intent.id }; revision++ } + is RemoteSessionIntent.PromoteQueuedMessage -> { items = items.filterNot { it.id == intent.id }; revision++ } + else -> Unit + } + } + } + } + } + } + } +} diff --git a/src/apps/mobile/android/app/src/main/res/values-zh/strings.xml b/src/apps/mobile/android/app/src/main/res/values-zh/strings.xml index 5d7d9b8801..23e3b6a6c8 100644 --- a/src/apps/mobile/android/app/src/main/res/values-zh/strings.xml +++ b/src/apps/mobile/android/app/src/main/res/values-zh/strings.xml @@ -485,4 +485,16 @@ 未配置快速模型,使用主力模型 主力 快速 + 待发送 · %1$d + 长按拖动排序 + 上移 + 下移 + 刷新 + 队列状态已变化或未能确认,请刷新后再操作。 + %1$d 个附件 + 等待执行端处理 + 立即发送 + 消息操作 + 从队列移除 + 升级执行端后可调整消息顺序。 diff --git a/src/apps/mobile/android/app/src/main/res/values/strings.xml b/src/apps/mobile/android/app/src/main/res/values/strings.xml index fedfeaf6c0..59e00b52ed 100644 --- a/src/apps/mobile/android/app/src/main/res/values/strings.xml +++ b/src/apps/mobile/android/app/src/main/res/values/strings.xml @@ -500,4 +500,16 @@ Fast model not configured; using primary Primary Fast + Queued messages · %1$d + Hold to reorder + Move up + Move down + Refresh + Queue status changed or could not be confirmed. Refresh before another action. + %1$d attachments + Waiting for host confirmation + Send now + Message actions + Remove from queue + Update the execution host to reorder messages. diff --git a/src/apps/mobile/design-system/components/mobile-components.json b/src/apps/mobile/design-system/components/mobile-components.json index c1244a0b62..202a5d960f 100644 --- a/src/apps/mobile/design-system/components/mobile-components.json +++ b/src/apps/mobile/design-system/components/mobile-components.json @@ -268,6 +268,33 @@ "content_on_action" ], "platformNotes": "Reference: desktop ChatInputApprovalBand and @openbitfun/ui raised Card, neutral resource Card, fill reject Button and primary allow Button. Preserve desktop 12-unit card radius/padding and 8-unit gaps, with 36-unit mobile actions. Resource content scrolls within the band; actions do not stretch across the card. JSON editing remains a quiet, collapsed mobile-web capability. status_warning ports desktop amber.550 for the short shield glyph: neither success/danger nor the blue file-link accent communicates pending approval." + }, + "message_queue": { + "purpose": "Manage the execution host’s pending messages without leaving the composer.", + "anatomy": [ + "count_disclosure", + "drag_handle", + "preview_and_attachments", + "send_now", + "actions_menu", + "inset_separator" + ], + "states": [ + "queued", + "blocked", + "steering_pending", + "reordering", + "offline", + "legacy_host" + ], + "tokens": [ + "content_gutter", + "control_touch_size", + "ink", + "muted", + "line" + ], + "platformNotes": "No enclosing border. Each 48pt row starts with a hairline inset by 8pt on both sides. The last row has no bottom separator and touches the composer without an extra gap. Attachments follow text. Native drag handles and accessible Move up/Move down actions commit through the host queue revision; incoming host changes cancel the gesture. Never present a local-only order as execution order." } } } diff --git a/src/apps/mobile/design-system/preview/generated/mobile-design-data.js b/src/apps/mobile/design-system/preview/generated/mobile-design-data.js index 1c76a85aec..807e3c77a3 100644 --- a/src/apps/mobile/design-system/preview/generated/mobile-design-data.js +++ b/src/apps/mobile/design-system/preview/generated/mobile-design-data.js @@ -1313,6 +1313,33 @@ export const mobileComponents = { "content_on_action" ], "platformNotes": "Reference: desktop ChatInputApprovalBand and @openbitfun/ui raised Card, neutral resource Card, fill reject Button and primary allow Button. Preserve desktop 12-unit card radius/padding and 8-unit gaps, with 36-unit mobile actions. Resource content scrolls within the band; actions do not stretch across the card. JSON editing remains a quiet, collapsed mobile-web capability. status_warning ports desktop amber.550 for the short shield glyph: neither success/danger nor the blue file-link accent communicates pending approval." + }, + "message_queue": { + "purpose": "Manage the execution host’s pending messages without leaving the composer.", + "anatomy": [ + "count_disclosure", + "drag_handle", + "preview_and_attachments", + "send_now", + "actions_menu", + "inset_separator" + ], + "states": [ + "queued", + "blocked", + "steering_pending", + "reordering", + "offline", + "legacy_host" + ], + "tokens": [ + "content_gutter", + "control_touch_size", + "ink", + "muted", + "line" + ], + "platformNotes": "No enclosing border. Each 48pt row starts with a hairline inset by 8pt on both sides. The last row has no bottom separator and touches the composer without an extra gap. Attachments follow text. Native drag handles and accessible Move up/Move down actions commit through the host queue revision; incoming host changes cancel the gesture. Never present a local-only order as execution order." } } }; diff --git a/src/apps/mobile/harmonyos/AGENTS.md b/src/apps/mobile/harmonyos/AGENTS.md index 8d750879ef..b1a0a68e9d 100644 --- a/src/apps/mobile/harmonyos/AGENTS.md +++ b/src/apps/mobile/harmonyos/AGENTS.md @@ -202,3 +202,12 @@ node --test src/apps/mobile/harmonyos/tools/tests/workspace-editor.test.cjs The Chrome renderer test does not replace Harmony device-level keyboard and sheet-layout checks. + +For queue capability negotiation, session isolation and mutation/read races: + +```bash +node --test tools/tests/message-queue.test.cjs +``` + +The fixture uses the production queue store with a simulated host. Native drag +presentation and live remote dispatch need separate device verification. diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/EnUsMessages.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/EnUsMessages.ets index 320a09e98f..cb5dfaa7c2 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/EnUsMessages.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/EnUsMessages.ets @@ -1,4 +1,16 @@ export const EN_US_MESSAGES: [string, string][] = [ + ['queue.title', 'Queued messages · %1$s'], + ['queue.reorder', 'Drag to reorder'], + ['queue.moveUp', 'Move up'], + ['queue.moveDown', 'Move down'], + ['queue.refresh', 'Refresh'], + ['queue.refreshRequired', 'Queue status changed or could not be confirmed. Refresh before another action.'], + ['queue.attachments', '%1$s attachments'], + ['queue.waiting', 'Waiting for the execution host'], + ['queue.sendNow', 'Send now'], + ['queue.more', 'Message actions'], + ['queue.remove', 'Remove from queue'], + ['queue.unsupported', 'Update the execution host to reorder messages.'], ['session.newTitle', 'New Session'], ['workspaceTools.browse', 'Browse runtime folders'], ['workspaceTools.selectFolder', 'Use this folder'], diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/ZhCnMessages.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/ZhCnMessages.ets index 3803d59f54..bcaa485eca 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/ZhCnMessages.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/i18n/ZhCnMessages.ets @@ -1,4 +1,16 @@ export const ZH_CN_MESSAGES: [string, string][] = [ + ['queue.title', '待发送 · %1$s'], + ['queue.reorder', '拖动排序'], + ['queue.moveUp', '上移'], + ['queue.moveDown', '下移'], + ['queue.refresh', '刷新'], + ['queue.refreshRequired', '队列状态已变化或未能确认,请刷新后再操作。'], + ['queue.attachments', '%1$s 个附件'], + ['queue.waiting', '等待执行端处理'], + ['queue.sendNow', '立即发送'], + ['queue.more', '消息操作'], + ['queue.remove', '从队列移除'], + ['queue.unsupported', '升级执行端后可调整消息顺序。'], ['session.newTitle', '新会话'], ['workspaceTools.browse', '浏览受控设备文件夹'], ['workspaceTools.selectFolder', '选择此文件夹'], diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/model/MessageQueue.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/model/MessageQueue.ets new file mode 100644 index 0000000000..cb04468ebb --- /dev/null +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/model/MessageQueue.ets @@ -0,0 +1,19 @@ + +export interface MessageQueueRequest { + sessionId: string; action: string; queueEpoch?: string; turnId?: string; + operationId?: string; expectedRevision?: number; beforeTurnId?: string; + expectedActiveTurnId?: string; +} +export interface MessageQueueItem { + turnId: string; displayContent: string; attachmentCount: number; status: string; reason?: string; +} +export interface MessageQueueSnapshot { + sessionId: string; queueEpoch: string; revision: number; items: MessageQueueItem[]; + supportsReorder?: boolean; activeTurnId?: string; +} +export interface MessageQueueResponse { resp?: string; message?: string; snapshot?: MessageQueueSnapshot; } +export class MessageQueueState { + sessionId: string = ''; items: MessageQueueItem[] = []; supportsReorder: boolean = false; + revisionKey: string = ''; busy: boolean = false; failure: string = ''; +} +export interface MessageQueueAction { sessionId: string; action: string; turnId?: string; beforeTurnId?: string; } diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/model/RemoteModels.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/model/RemoteModels.ets index 3f8cda3600..00b8f518e2 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/model/RemoteModels.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/model/RemoteModels.ets @@ -1,3 +1,4 @@ +import { MessageQueueRequest } from './MessageQueue'; export interface RuntimeFileLocation { path: string; remoteConnectionId?: string; } @@ -129,6 +130,7 @@ export interface SavedRuntimeConnection { id: string; name: string; host: string export interface SavedRuntimeConnectionsResponse extends CommandStatusResponse { ok: boolean; value?: SavedRuntimeConnection[]; error?: string; } export interface RemoteCommand { + request?: MessageQueueRequest; workspace_id?: string; remote_ssh_host?: string; command?: string; diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntent.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntent.ets index f600afe402..32b9696a87 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntent.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntent.ets @@ -1,8 +1,10 @@ +import { MessageQueueAction } from '../../model/MessageQueue'; import { InteractionMailboxAction } from '../../model/InteractionMailbox'; import { ConversationUiQuestionAnswer } from '../state/ConversationUiModels'; import { FilePreviewRequest } from '../../model/FilePreviewTarget'; export enum ConversationIntentType { + MessageQueue = 'message_queue', Mailbox = 'mailbox', OpenSidebar = 'open_sidebar', Back = 'back', @@ -145,6 +147,7 @@ export class ConversationIntent { rollbackRequest?: SessionRollbackRequest; readonly copyScope: MessageCopyScope; readonly commandPaletteRequest?: CommandPaletteRequest; + queueAction?: MessageQueueAction; mailboxAction?: InteractionMailboxAction; constructor( @@ -171,6 +174,9 @@ export class ConversationIntent { } export class ConversationIntents { + static queue(action: MessageQueueAction): ConversationIntent { + const intent = new ConversationIntent(ConversationIntentType.MessageQueue); intent.queueAction = action; return intent; + } static mailbox(action: InteractionMailboxAction): ConversationIntent { const intent = new ConversationIntent(ConversationIntentType.Mailbox); intent.mailboxAction = action; diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntentDispatcher.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntentDispatcher.ets index 74cefb3ba3..7db924d5cc 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntentDispatcher.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/actions/ConversationIntentDispatcher.ets @@ -1,3 +1,4 @@ +import { MessageQueueAction } from '../../model/MessageQueue'; import { InteractionMailboxAction } from '../../model/InteractionMailbox'; import { RemoteQuestionAnswerPayload, RemoteSession } from '../../model/RemoteModels'; import { AppRoute, AppRouteContract } from '../navigation/AppRouteContract'; @@ -6,6 +7,7 @@ import { toRemoteQuestionAnswer } from '../state/ConversationUiModels'; import { FilePreviewRequest } from '../../model/FilePreviewTarget'; export interface ConversationIntentDispatcherHooks { + readonly queue?: (action: MessageQueueAction) => Promise; readonly mailbox: (action: InteractionMailboxAction) => Promise; readonly openSidebar: () => void; readonly back: () => void; @@ -53,6 +55,7 @@ export class ConversationIntentDispatcher { dispatch(route: AppRoute, intent: ConversationIntent): void { switch (intent.type) { + case ConversationIntentType.MessageQueue: if (route === AppRoute.RemoteChat && intent.queueAction) void this.hooks.queue?.(intent.queueAction); return; case ConversationIntentType.Mailbox: if (intent.mailboxAction) void this.hooks.mailbox(intent.mailboxAction); return; case ConversationIntentType.OpenSidebar: this.hooks.openSidebar(); return; case ConversationIntentType.Back: this.hooks.back(); return; diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ComposerBar.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ComposerBar.ets index 3160df57eb..d128c0833e 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ComposerBar.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ComposerBar.ets @@ -62,6 +62,7 @@ const COMPOSER_MODEL_DEFAULTS_DIVIDER_MARGIN_TOP: number = 4; @ComponentV2 export struct ComposerBar { + @Param queueAttached: boolean = false; @Param presentation: ComposerPresentation = ComposerPresentation.Compact; @Param capabilities: ChatComposerCapabilities = REMOTE_CHAT_COMPOSER_CAPABILITIES; @Param inputId: string = 'conversation-composer-input'; @@ -177,7 +178,7 @@ export struct ComposerBar { ? 24 : MobileDesignGeometry.conversationOverlaySideInset, right: this.presentation === ComposerPresentation.Floating ? 24 : MobileDesignGeometry.conversationOverlaySideInset, - top: 8, + top: this.queueAttached ? 0 : 8, bottom: this.presentation === ComposerPresentation.Floating ? 16 : 12 }) .backgroundColor(TRANSPARENT) diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationView.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationView.ets index b30ce19a36..f31af5689b 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationView.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/ConversationView.ets @@ -1,3 +1,5 @@ +import { MessageQueuePanel } from './MessageQueuePanel'; +import { MessageQueueAction } from '../../model/MessageQueue'; import { InteractionMailboxPanel } from './InteractionMailboxPanel'; import { InteractionMailboxAction } from '../../model/InteractionMailbox'; import { MobileDesignGeometry, MobileDesignTypography } from '../../generated/MobileDesignTokens'; @@ -654,7 +656,11 @@ export struct ConversationView { this.applyRollbackEvent({ type: SessionRollbackEventType.CloseStaging }); } }) + if (this.surface === ChatSurface.Remote && this.state.messageQueue.sessionId === this.state.activeSession.sessionId) { + MessageQueuePanel({ state: this.state.messageQueue, onAction: (action: MessageQueueAction): void => { this.onIntent(ConversationIntents.queue(action)); } }) + } ComposerBar({ + queueAttached: this.surface === ChatSurface.Remote && this.state.messageQueue.sessionId === this.state.activeSession.sessionId && (this.state.messageQueue.items.length > 0 || this.state.messageQueue.failure.length > 0), presentation: this.composerPresentation, capabilities: this.composerCapabilities, inputId: this.composerInputId, diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MessageQueuePanel.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MessageQueuePanel.ets new file mode 100644 index 0000000000..4e78f67c5a --- /dev/null +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/components/MessageQueuePanel.ets @@ -0,0 +1,91 @@ +import { MessageQueueAction, MessageQueueItem, MessageQueueState } from '../../model/MessageQueue'; +import { RemoteI18n } from '../../i18n/RemoteI18n'; +import { MobileDesignTypography, MobileDesignGeometry } from '../../generated/MobileDesignTokens'; +import { INK, LINE, MUTED, TRANSPARENT, CARD } from './Theme'; + +@ComponentV2 +export struct MessageQueuePanel { + @Param state: MessageQueueState = new MessageQueueState(); + @Event onAction: (action: MessageQueueAction) => void = (_action: MessageQueueAction): void => {}; + @Local expanded: boolean = true; + @Local dragging: string = ''; + @Local dragOffset: number = 0; + @Local before: string = ''; + @Local dragRevision: string = ''; + @Monitor('state.revisionKey', 'state.busy', 'state.failure') + resetGesture(): void { this.dragging = ''; this.dragOffset = 0; } + + private queued(): MessageQueueItem[] { return this.state.items.filter((item: MessageQueueItem): boolean => item.status === 'queued'); } + private canMove(item: MessageQueueItem): boolean { return this.state.supportsReorder && !this.state.busy && !this.state.failure && item.status === 'queued' && this.queued().length > 1; } + private move(item: MessageQueueItem, delta: number): void { + const items = this.queued(); + const index = items.findIndex((value: MessageQueueItem): boolean => value.turnId === item.turnId); + if (!this.canMove(item) || index + delta < 0 || index + delta >= items.length) return; + this.onAction({ sessionId: this.state.sessionId, action: 'reorder', turnId: item.turnId, beforeTurnId: delta < 0 ? items[index - 1].turnId : items[index + 2]?.turnId }); + } + @Builder + Actions(item: MessageQueueItem) { + Menu() { + MenuItem({ content: item.displayContent }).enabled(false) + if (!this.state.supportsReorder) { MenuItem({ content: RemoteI18n.t('queue.unsupported') }).enabled(false) } + MenuItem({ content: RemoteI18n.t('queue.moveUp') }).enabled(this.canMove(item) && this.queued()[0]?.turnId !== item.turnId).onClick((): void => this.move(item, -1)) + MenuItem({ content: RemoteI18n.t('queue.moveDown') }).enabled(this.canMove(item) && this.queued().slice(-1)[0]?.turnId !== item.turnId).onClick((): void => this.move(item, 1)) + MenuItem({ content: RemoteI18n.t('queue.remove') }).enabled(!this.state.busy && !this.state.failure && item.status !== 'steering_pending') + .onClick((): void => this.onAction({ sessionId: this.state.sessionId, action: 'cancel', turnId: item.turnId })) + } + } + @Builder + MessageRow(item: MessageQueueItem, index: number) { + Column() { + Divider().color(LINE).strokeWidth(0.5).margin({ left: 8, right: 8 }) + Row({ space: 4 }) { + if (this.state.supportsReorder) { + Column({ space: 3 }) { ForEach([0, 1, 2], (): void => { Divider().color(MUTED).strokeWidth(1).width(14) }) } + .width(44).height(48).justifyContent(FlexAlign.Center).accessibilityText(RemoteI18n.t('queue.reorder')) + .gesture(PanGesture({ direction: PanDirection.Vertical, distance: 6 }) + .onActionStart((): void => { if (this.canMove(item)) { this.dragging = item.turnId; this.dragRevision = this.state.revisionKey; this.dragOffset = 0; this.before = ''; } }) + .onActionUpdate((event: GestureEvent): void => { + if (this.dragging !== item.turnId || !this.canMove(item)) return; + this.dragOffset = event.offsetY; + const target = Math.max(0, Math.min(this.state.items.length - 1, index + Math.round(this.dragOffset / 49))); + const rest = this.state.items.filter((value: MessageQueueItem): boolean => value.turnId !== item.turnId); + this.before = rest.slice(target).find((value: MessageQueueItem): boolean => value.status === 'queued')?.turnId || ''; + }) + .onActionEnd((): void => { + if (this.dragging === item.turnId && this.dragRevision === this.state.revisionKey && this.canMove(item) && Math.abs(this.dragOffset) > 24) this.onAction({ sessionId: this.state.sessionId, action: 'reorder', turnId: item.turnId, beforeTurnId: this.before || undefined }); + this.dragging = ''; this.dragOffset = 0; + }).onActionCancel((): void => { this.dragging = ''; this.dragOffset = 0; })) + } + Column({ space: 2 }) { + Row({ space: 6 }) { + Text(item.displayContent).fontSize(MobileDesignTypography.bodyMedium.size).fontColor(INK).maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }).flexShrink(1) + if (item.attachmentCount > 0) { Text(RemoteI18n.f('queue.attachments', `${item.attachmentCount}`)).fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED).flexShrink(0) } + }.width('100%') + if (item.status !== 'queued') { Text(RemoteI18n.t('queue.waiting')).fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED) } + }.layoutWeight(1).alignItems(HorizontalAlign.Start) + Button({ type: ButtonType.Normal }) { SymbolGlyph($r('sys.symbol.arrow_up')).fontSize(16).fontColor([MUTED]) } + .width(44).height(48).backgroundColor(TRANSPARENT).accessibilityText(RemoteI18n.t('queue.sendNow')).enabled(!this.state.busy && !this.state.failure && item.status !== 'steering_pending') + .onClick((): void => this.onAction({ sessionId: this.state.sessionId, action: 'promote', turnId: item.turnId })) + Button({ type: ButtonType.Normal }) { Image($r('app.media.remote_ref_more')).width(16).height(16).fillColor(MUTED).renderMode(ImageRenderMode.Template) } + .width(44).height(48).backgroundColor(TRANSPARENT).accessibilityText(RemoteI18n.t('queue.more')).bindMenu(this.Actions(item)) + }.width('100%').height(48) + }.width('100%').translate({ y: this.dragging === item.turnId ? this.dragOffset : 0 }).backgroundColor(this.dragging === item.turnId ? CARD : TRANSPARENT).zIndex(this.dragging === item.turnId ? 1 : 0) + } + build() { + if (this.state.items.length > 0 || this.state.failure.length > 0) { + Column() { + Row({ space: 6 }) { + Text(RemoteI18n.f('queue.title', `${this.state.items.length}`)).fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED) + SymbolGlyph(this.expanded ? $r('sys.symbol.chevron_down') : $r('sys.symbol.chevron_up')).fontSize(12).fontColor([MUTED]) + }.width('100%').height(40).onClick((): void => { this.expanded = !this.expanded; }) + if (this.state.failure.length > 0) { + Row() { + Text(RemoteI18n.t(this.state.failure === 'unsupported' ? 'queue.unsupported' : 'queue.refreshRequired')).fontSize(MobileDesignTypography.bodySmall.size).fontColor(MUTED).layoutWeight(1) + Button(RemoteI18n.t('queue.refresh')).fontColor(INK).backgroundColor(TRANSPARENT).height(44).onClick((): void => this.onAction({ sessionId: this.state.sessionId, action: 'list' })) + } + } + if (this.expanded) { Scroll() { Column() { ForEach(this.state.items, (item: MessageQueueItem, index: number): void => { this.MessageRow(item, index) }, (item: MessageQueueItem): string => item.turnId) } }.constraintSize({ maxHeight: 196 }).scrollBar(BarState.Auto) } + }.width('100%').padding({ left: MobileDesignGeometry.contentGutter, right: MobileDesignGeometry.contentGutter }) + } + } +} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntimeComposition.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntimeComposition.ets index 7faa4f8deb..9097816d56 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntimeComposition.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/runtime/AppRootRuntimeComposition.ets @@ -1,3 +1,4 @@ +import { MessageQueueAction, MessageQueueState } from '../../model/MessageQueue'; import { InteractionMailboxAction, InteractionMailboxState } from '../../model/InteractionMailbox'; import { HostCatalogChange, HostCatalogObserver } from '../../services/HostCatalogObserver'; import { WorkspaceToolsViewModel } from '../viewmodel/WorkspaceToolsViewModel'; @@ -527,6 +528,9 @@ export abstract class AppRootRuntimeComposition { this.isRemoteConversationContext(sessionId) && this.remoteConnectionController.ensureAvailable(); }, + onQueue: (state: MessageQueueState): void => { + if (!state.sessionId || this.remotePageState.activeSession.sessionId === state.sessionId) this.remotePageState.messageQueue = state; + }, onMailbox: (state: InteractionMailboxState): void => { if (!state.sessionId || this.remotePageState.activeSession.sessionId === state.sessionId) { this.remotePageState.interactionMailbox = state; @@ -832,6 +836,7 @@ export abstract class AppRootRuntimeComposition { ); readonly conversationIntentDispatcher: ConversationIntentDispatcher = new ConversationIntentDispatcher({ + queue: async (action: MessageQueueAction): Promise => { await this.remoteChatPollingLifecycleController.dispatchQueue(action); }, mailbox: async (action: InteractionMailboxAction): Promise => { await this.remoteChatPollingLifecycleController.dispatchMailbox(action); }, openSidebar: (): void => this.openAppSidebar(), back: (): void => this.exitActiveChat(), diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationViewState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationViewState.ets index 020ecfc111..4a67a62074 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationViewState.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/ConversationViewState.ets @@ -1,3 +1,4 @@ +import { MessageQueueState } from '../../model/MessageQueue'; import { InteractionMailboxState } from '../../model/InteractionMailbox'; import { ObservableChatTimelineItem } from '../../model/ChatTimelineModels'; import { @@ -28,6 +29,7 @@ import { RollbackEntryFacts } from '../policy/RollbackPresentationPolicy'; /** Immutable presentation state consumed by ConversationView. */ export class ConversationViewState { + messageQueue: MessageQueueState = new MessageQueueState(); interactionMailbox: InteractionMailboxState = new InteractionMailboxState(); activeSession: ConversationUiSession = ConversationViewState.emptySession(); surface: ChatSurface = ChatSurface.General; @@ -117,6 +119,7 @@ export class ConversationViewState { state.downloadedFilePath = remote.downloadedFilePath; state.fileDownloadStatus = remote.fileDownloadStatus; state.interactionMailbox = remote.interactionMailbox; + state.messageQueue = remote.messageQueue; state.commandPalette = CommandPalettePresentation.project( remote.commandPalette, state.activeSession.sessionId.length > 0, diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/RemotePageState.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/RemotePageState.ets index beda144bc4..bec9860e8b 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/RemotePageState.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/state/RemotePageState.ets @@ -1,3 +1,4 @@ +import { MessageQueueState } from '../../model/MessageQueue'; import { TimeFormat } from '../../services/TimeFormat'; import { InteractionMailboxState } from '../../model/InteractionMailbox'; import { WorkspaceToolsState } from './WorkspaceToolsState'; @@ -24,6 +25,7 @@ import { CommandPaletteState } from './CommandPaletteState'; */ @ObservedV2 export class RemotePageState { + @Trace messageQueue: MessageQueueState = new MessageQueueState(); @Trace interactionMailbox: InteractionMailboxState = new InteractionMailboxState(); readonly workspaceTools: WorkspaceToolsState = new WorkspaceToolsState(); /** @@ -288,6 +290,7 @@ export class RemotePageState { if (this.conversation.activeSession.sessionId !== session.sessionId) { this.sessionContextRevision += 1; this.interactionMailbox = new InteractionMailboxState(); + this.messageQueue = new MessageQueueState(); this.clearRollbackNotice(); this.clearRollbackOutcome(); // A skill catalog, a usage report and a lit goal chip all belong to the @@ -303,6 +306,7 @@ export class RemotePageState { this.clearRollbackNotice(); this.clearRollbackOutcome(); this.interactionMailbox = new InteractionMailboxState(); + this.messageQueue = new MessageQueueState(); this.commandPalette.reset(); this.conversation.clearActiveSession(); this.isLoadingConversation = false; @@ -494,6 +498,7 @@ export class RemotePageState { resetConversationContext(): void { this.sessionContextRevision += 1; this.interactionMailbox = new InteractionMailboxState(); + this.messageQueue = new MessageQueueState(); this.commandPalette.reset(); this.conversation.reset(); this.hasMoreSessions = false; diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatSessionController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatSessionController.ets index 34295086f1..76a7f11824 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatSessionController.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/ChatSessionController.ets @@ -1,3 +1,5 @@ +import { MessageQueueStore } from './MessageQueueStore'; +import { MessageQueueAction, MessageQueueState } from '../model/MessageQueue'; import { InteractionMailboxStore } from './InteractionMailboxStore'; import { InteractionMailboxAction, InteractionMailboxState } from '../model/InteractionMailbox'; import { DurableSessionReducer } from './DurableSessionReducer'; @@ -42,6 +44,7 @@ export interface ChatSessionSnapshot { export interface ChatSessionControllerCallbacks { onSnapshot: (snapshot: ChatSessionSnapshot) => void; + onQueue?: (state: MessageQueueState) => void; onMailbox?: (state: InteractionMailboxState) => void; onError: (error: Object) => void; canPoll: (sessionId: string) => boolean; @@ -70,6 +73,7 @@ export class ChatSessionController { private cursor: ChatSessionCursor = { pollVersion: 0, knownMessageCount: 0, knownModelCatalogVersion: 0 }; private stream?: HostSessionStream; private reducer: DurableSessionReducer = new DurableSessionReducer(); + private messageQueue: MessageQueueStore; private mailbox: InteractionMailboxStore; private subagents: SubagentStreamCoordinator; private generation: number = 0; @@ -87,6 +91,7 @@ export class ChatSessionController { constructor(sessionManager: RemoteSessionManager, callbacks: ChatSessionControllerCallbacks, options?: ChatSessionControllerOptions) { this.sessionManager = sessionManager; this.callbacks = callbacks; + this.messageQueue = new MessageQueueStore(sessionManager, (state: MessageQueueState): void => { this.callbacks.onQueue?.(state); }, callbacks.canPoll); this.mailbox = new InteractionMailboxStore(sessionManager, (state: InteractionMailboxState): void => { this.callbacks.onMailbox?.(state); }); // A delegation tool's child sessions are streams of their own; they are read // while this session is open and their records land in the branch of the @@ -101,7 +106,7 @@ export class ChatSessionController { this.stream.wake(); return; } this.stop(); this.sessionId = sessionId; this.cursor = cursor; - this.reducer = new DurableSessionReducer(); this.mailbox.select(sessionId); this.stopped = false; this.caughtUp = false; + this.reducer = new DurableSessionReducer(); this.mailbox.select(sessionId); this.messageQueue.select(sessionId); this.stopped = false; this.caughtUp = false; this.sessionState = 'idle'; this.completedTurnId = ''; this.hasMoreMessages = false; this.historyLoading = false; this.historyReplaying = false; this.historyFailed = false; this.pendingModelCatalog = undefined; @@ -162,7 +167,7 @@ export class ChatSessionController { } } stop(_clearActiveTurn: boolean = true): void { - this.generation++; this.stopped = true; this.mailbox.select(''); this.stream?.close(); this.stream = undefined; + this.generation++; this.stopped = true; this.mailbox.select(''); this.messageQueue.select(''); this.stream?.close(); this.stream = undefined; this.subagents.endSession(); } loadOlder(): void { this.stream?.loadOlder(); } @@ -175,6 +180,7 @@ export class ChatSessionController { } setKnownMessageCount(count: number): void { this.cursor.knownMessageCount = count; } clearActiveTurn(): void { /* Runtime message/state events own turn lifetime. */ } + async dispatchQueue(action: MessageQueueAction): Promise { if (!this.stopped) await this.messageQueue.dispatch(action); } async dispatchMailbox(action: InteractionMailboxAction): Promise { if (!this.stopped && action.sessionId === this.sessionId) await this.mailbox.dispatch(action); } diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/MessageQueueStore.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/MessageQueueStore.ets new file mode 100644 index 0000000000..b84478c72b --- /dev/null +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/MessageQueueStore.ets @@ -0,0 +1,87 @@ +import { MessageQueueAction, MessageQueueItem, MessageQueueRequest, MessageQueueSnapshot, MessageQueueState } from '../model/MessageQueue'; +import { RemoteSessionManager } from './RemoteSessionManager'; +import { Encoding } from './Encoding'; + +/** A controller replica; the execution host owns both receipts and dispatch order. */ +export class MessageQueueStore { + private client: RemoteSessionManager; + private onChange: (state: MessageQueueState) => void; + private canPoll: (sessionId: string) => boolean; + private state: MessageQueueState = new MessageQueueState(); + private snapshot?: MessageQueueSnapshot; + private generation: number = 0; + private timer: number = -1; + private reading: boolean = false; + private readVersion: number = 0; + constructor(client: RemoteSessionManager, onChange: (state: MessageQueueState) => void, canPoll: (sessionId: string) => boolean) { + this.client = client; this.onChange = onChange; this.canPoll = canPoll; + } + select(sessionId: string): void { + this.generation++; + if (this.timer >= 0) clearTimeout(this.timer); + this.timer = -1; this.reading = false; this.snapshot = undefined; + this.state = new MessageQueueState(); this.state.sessionId = sessionId; this.publish(); + if (sessionId) void this.refresh(); + } + private accept(value: MessageQueueSnapshot): void { + if (value.sessionId !== this.state.sessionId || !value.queueEpoch || !Array.isArray(value.items)) throw new Error('Invalid queue snapshot'); + if (this.snapshot?.queueEpoch === value.queueEpoch && this.snapshot.revision > value.revision) return; + this.snapshot = value; this.state.revisionKey = `${value.queueEpoch}:${value.revision}`; this.state.items = value.items.slice(); this.state.supportsReorder = value.supportsReorder === true; + this.state.failure = ''; this.publish(); + } + async refresh(): Promise { + if (this.reading || this.state.busy || !this.state.sessionId) return; + if (this.timer >= 0) clearTimeout(this.timer); + const ticket = this.generation; + const version = this.readVersion; + this.reading = true; + try { + if (!this.canPoll(this.state.sessionId)) { + this.state.failure = 'offline'; this.publish(); + } else if (!this.client.supportsMessageQueue()) { + if (this.state.items.length > 0) { this.state.failure = 'unsupported'; this.state.supportsReorder = false; this.publish(); } + } else { + const value = await this.client.manageMessageQueue({ sessionId: this.state.sessionId, action: 'list' }); + if (ticket === this.generation && version === this.readVersion) this.accept(value); + } + } catch (_error) { if (ticket === this.generation && version === this.readVersion) { this.state.failure = 'load'; this.publish(); } } + finally { + if (ticket === this.generation) { + this.reading = false; + this.timer = setTimeout((): void => { void this.refresh(); }, this.state.items.length > 0 ? 2000 : 10000); + } + } + } + async dispatch(action: MessageQueueAction): Promise { + if (action.sessionId !== this.state.sessionId) return; + if (action.action === 'list') { await this.refresh(); return; } + const observed = this.snapshot; + if (!observed || this.state.busy || this.state.failure) return; + if (!this.canPoll(action.sessionId)) { this.state.failure = 'offline'; this.publish(); return; } + const item = this.state.items.find((value: MessageQueueItem): boolean => value.turnId === action.turnId); + if (!item || (item.status !== 'queued' && item.status !== 'blocked')) return; + if (action.action === 'reorder' && (!observed.supportsReorder || item.status !== 'queued')) { + this.state.failure = 'unsupported'; this.publish(); return; + } + const ticket = this.generation; + this.readVersion++; + this.state.busy = true; this.publish(); + const request: MessageQueueRequest = { sessionId: action.sessionId, action: action.action, queueEpoch: observed.queueEpoch, + turnId: item.turnId, operationId: Encoding.randomId('queue'), beforeTurnId: action.beforeTurnId, + expectedRevision: observed.revision, expectedActiveTurnId: observed.activeTurnId }; + try { + const value = await this.client.manageMessageQueue(request); + if (ticket !== this.generation) return; + if (value.queueEpoch !== observed.queueEpoch) throw new Error('Queue owner changed'); + this.accept(value); + } catch (_error) { if (ticket === this.generation) { this.state.failure = 'unknown'; this.publish(); } } + finally { + if (ticket === this.generation) { this.state.busy = false; this.publish(); void this.refresh(); } + } + } + private publish(): void { + const next = new MessageQueueState(); + next.sessionId = this.state.sessionId; next.items = this.state.items.slice(); next.supportsReorder = this.state.supportsReorder; + next.revisionKey = this.state.revisionKey; next.busy = this.state.busy; next.failure = this.state.failure; this.onChange(next); + } +} diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatPollingLifecycleController.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatPollingLifecycleController.ets index 40ec7630f5..daaf72f1e4 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatPollingLifecycleController.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteChatPollingLifecycleController.ets @@ -1,3 +1,4 @@ +import { MessageQueueAction } from '../model/MessageQueue'; import { InteractionMailboxAction } from '../model/InteractionMailbox'; import { ChatMessage } from '../model/RemoteModels'; import { @@ -42,6 +43,7 @@ export class RemoteChatPollingLifecycleController { this.controller.stop(); } + async dispatchQueue(action: MessageQueueAction): Promise { await this.controller.dispatchQueue(action); } async dispatchMailbox(action: InteractionMailboxAction): Promise { await this.controller.dispatchMailbox(action); } async refreshModelCatalog(): Promise { await this.controller.refreshModelCatalog(); } diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionManager.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionManager.ets index f8fa263dfd..fd1b445c5a 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionManager.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/RemoteSessionManager.ets @@ -1,3 +1,4 @@ +import { MessageQueueRequest, MessageQueueResponse, MessageQueueSnapshot } from '../model/MessageQueue'; import { WorkspaceCatalog, projectWorkspaceCatalog } from './WorkspaceCatalog'; import { RuntimeFileLocation } from '../model/RemoteModels'; import { HostSessionCallbacks, HostSessionStream, REMOTE_CAPABILITY_HOST_STREAM_V1 } from './HostSessionStream'; @@ -111,6 +112,14 @@ export class RemoteSessionManager implements RemoteChatCommandClient, RemoteFile * caller can tell a host that answered from a connection that did not: only the * first may be described to the user as the host's own decision. */ + supportsMessageQueue(): boolean { return this.hostCapabilities.includes('dialog_queue_v1'); } + async manageMessageQueue(request: MessageQueueRequest): Promise { + if (!this.supportsMessageQueue()) throw new Error('Host message queue is unsupported'); + const response = await this.send({ cmd: 'dialog_queue', request: request }); + if (response.resp === 'error' || !response.snapshot) throw new Error(response.message || 'Queue request failed'); + return response.snapshot; + } + async hostInvoke(command: string, args: Object): Promise { const response = await this.send>({ cmd: 'host_invoke', command: command, args: args }); if (!response.ok) throw new HostInvokeRefusal(command, response.error || ''); diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/string.json b/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/string.json index 2de8f09c6b..c16dd31a06 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/string.json +++ b/src/apps/mobile/harmonyos/entry/src/main/resources/base/element/string.json @@ -19,6 +19,54 @@ { "name": "permission_distributed_datasync_reason", "value": "Used to authorize a watch on the same GitHub account using a separate device credential." + }, + { + "name": "queue_title", + "value": "待发送 · %1$s" + }, + { + "name": "queue_reorder", + "value": "拖动排序" + }, + { + "name": "queue_moveUp", + "value": "上移" + }, + { + "name": "queue_moveDown", + "value": "下移" + }, + { + "name": "queue_refresh", + "value": "刷新" + }, + { + "name": "queue_refreshRequired", + "value": "队列状态已变化或未能确认,请刷新后再操作。" + }, + { + "name": "queue_attachments", + "value": "%1$s 个附件" + }, + { + "name": "queue_waiting", + "value": "等待执行端处理" + }, + { + "name": "queue_sendNow", + "value": "立即发送" + }, + { + "name": "queue_more", + "value": "消息操作" + }, + { + "name": "queue_remove", + "value": "从队列移除" + }, + { + "name": "queue_unsupported", + "value": "升级执行端后可调整消息顺序。" } ] } diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/en_US/element/string.json b/src/apps/mobile/harmonyos/entry/src/main/resources/en_US/element/string.json index b3b5915996..0cd1131a2d 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/resources/en_US/element/string.json +++ b/src/apps/mobile/harmonyos/entry/src/main/resources/en_US/element/string.json @@ -3151,6 +3151,54 @@ { "name": "commands_skills_refusedBody", "value": "The connected desktop answered, and its answer was a refusal. The desktop text below is what it said; check the session and try again." + }, + { + "name": "queue_title", + "value": "Queued messages · %1$s" + }, + { + "name": "queue_reorder", + "value": "Drag to reorder" + }, + { + "name": "queue_moveUp", + "value": "Move up" + }, + { + "name": "queue_moveDown", + "value": "Move down" + }, + { + "name": "queue_refresh", + "value": "Refresh" + }, + { + "name": "queue_refreshRequired", + "value": "Queue status changed or could not be confirmed. Refresh before another action." + }, + { + "name": "queue_attachments", + "value": "%1$s attachments" + }, + { + "name": "queue_waiting", + "value": "Waiting for the execution host" + }, + { + "name": "queue_sendNow", + "value": "Send now" + }, + { + "name": "queue_more", + "value": "Message actions" + }, + { + "name": "queue_remove", + "value": "Remove from queue" + }, + { + "name": "queue_unsupported", + "value": "Update the execution host to reorder messages." } ] } diff --git a/src/apps/mobile/harmonyos/entry/src/main/resources/zh_CN/element/string.json b/src/apps/mobile/harmonyos/entry/src/main/resources/zh_CN/element/string.json index 84d65ccfd0..75c9c09ec8 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/resources/zh_CN/element/string.json +++ b/src/apps/mobile/harmonyos/entry/src/main/resources/zh_CN/element/string.json @@ -3151,6 +3151,54 @@ { "name": "commands_skills_refusedBody", "value": "桌面端有响应,但拒绝了请求。下方是桌面端的原文;请检查会话后重试。" + }, + { + "name": "queue_title", + "value": "待发送 · %1$s" + }, + { + "name": "queue_reorder", + "value": "拖动排序" + }, + { + "name": "queue_moveUp", + "value": "上移" + }, + { + "name": "queue_moveDown", + "value": "下移" + }, + { + "name": "queue_refresh", + "value": "刷新" + }, + { + "name": "queue_refreshRequired", + "value": "队列状态已变化或未能确认,请刷新后再操作。" + }, + { + "name": "queue_attachments", + "value": "%1$s 个附件" + }, + { + "name": "queue_waiting", + "value": "等待执行端处理" + }, + { + "name": "queue_sendNow", + "value": "立即发送" + }, + { + "name": "queue_more", + "value": "消息操作" + }, + { + "name": "queue_remove", + "value": "从队列移除" + }, + { + "name": "queue_unsupported", + "value": "升级执行端后可调整消息顺序。" } ] } diff --git a/src/apps/mobile/harmonyos/tools/tests/message-queue.test.cjs b/src/apps/mobile/harmonyos/tools/tests/message-queue.test.cjs new file mode 100644 index 0000000000..5f3e18af45 --- /dev/null +++ b/src/apps/mobile/harmonyos/tools/tests/message-queue.test.cjs @@ -0,0 +1,73 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const ts = require('typescript'); +function load(name, dependencies = {}) { + const code = ts.transpileModule(fs.readFileSync(path.join(__dirname, '../../entry/src/main/ets', name + '.ets'), 'utf8'), { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, + }).outputText; + const exports = {}; + new Function('require', 'exports', 'setTimeout', 'clearTimeout', code)(name => dependencies[name] || {}, exports, () => 1, () => {}); + return exports; +} +const model = load('model/MessageQueue'); +const { MessageQueueStore } = load('services/MessageQueueStore', { '../model/MessageQueue': model, './Encoding': { Encoding: { randomId: () => 'operation' } } }); +const snapshot = (sessionId = 's', revision = 7, ids = ['a', 'b']) => ({ sessionId, queueEpoch: 'owner', revision, supportsReorder: true, items: ids.map(turnId => ({ turnId, displayContent: turnId, status: 'queued', attachmentCount: 0 })) }); +const flush = () => new Promise(resolve => setImmediate(resolve)); +function fixture() { + const requests = []; + const f = { state: null, respond: async request => snapshot(request.sessionId) }; + f.store = new MessageQueueStore({ supportsMessageQueue: () => true, manageMessageQueue: async request => { requests.push(request); return f.respond(request); } }, state => { f.state = state; }, () => true); + f.requests = requests; + return f; +} +test('host-confirmed order and revision fence every move', async () => { + const f = fixture(); f.store.select('s'); await flush(); + let acknowledge; + f.respond = () => new Promise(resolve => { acknowledge = resolve; }); + const work = f.store.dispatch({ sessionId: 's', action: 'reorder', turnId: 'b', beforeTurnId: 'a' }); + assert.deepEqual(f.state.items.map(i => i.turnId), ['a', 'b']); + assert.equal(f.state.busy, true); + assert.equal(f.requests[1].expectedRevision, 7); + assert.equal(f.requests[1].queueEpoch, 'owner'); + f.respond = async () => snapshot('s', 8, ['b', 'a']); + acknowledge(snapshot('s', 8, ['b', 'a'])); await work; + assert.deepEqual(f.state.items.map(i => i.turnId), ['b', 'a']); + assert.equal(f.state.revisionKey, 'owner:8'); +}); +test('old hosts cannot reorder and stale-session actions never leave the controller', async () => { + const f = fixture(); f.respond = async () => { const value = snapshot(); delete value.supportsReorder; return value; }; + f.store.select('s'); await flush(); + await f.store.dispatch({ sessionId: 's', action: 'reorder', turnId: 'a' }); + assert.equal(f.state.failure, 'unsupported'); + await f.store.dispatch({ sessionId: 'other', action: 'cancel', turnId: 'a' }); + assert.equal(f.requests.length, 1); +}); +test('session switches fence late responses without removing the new session', async () => { + const f = fixture(); let release; + f.respond = () => new Promise(resolve => { release = resolve; }); + f.store.select('old'); + f.respond = async () => snapshot('new', 1, ['new-message']); + f.store.select('new'); await flush(); + release(snapshot('old')); await flush(); + assert.equal(f.state.sessionId, 'new'); + assert.deepEqual(f.state.items.map(i => i.turnId), ['new-message']); +}); +test('ambiguous mutation retains content and never replays the mutation', async () => { + const f = fixture(); f.store.select('s'); await flush(); + f.respond = async () => { throw new Error('Disconnected'); }; + await f.store.dispatch({ sessionId: 's', action: 'reorder', turnId: 'a' }); await flush(); + assert.deepEqual(f.state.items.map(i => i.turnId), ['a', 'b']); + assert.ok(f.state.failure); + await f.store.dispatch({ sessionId: 's', action: 'reorder', turnId: 'a' }); + assert.equal(f.requests.filter(r => r.action === 'reorder').length, 1); +}); +test('offline controllers retain the queue and report why mutations cannot run', async () => { + const f = fixture(); f.store.select('s'); await flush(); + f.store.canPoll = () => false; + await f.store.dispatch({ sessionId: 's', action: 'reorder', turnId: 'a' }); + assert.equal(f.state.failure, 'offline'); + assert.deepEqual(f.state.items.map(i => i.turnId), ['a', 'b']); + assert.equal(f.requests.length, 1); +}); diff --git a/src/apps/mobile/ios/OpenBitFun.xcodeproj/project.pbxproj b/src/apps/mobile/ios/OpenBitFun.xcodeproj/project.pbxproj index bca361c31a..c0cbb293bb 100644 --- a/src/apps/mobile/ios/OpenBitFun.xcodeproj/project.pbxproj +++ b/src/apps/mobile/ios/OpenBitFun.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + A91000000000000000000008 /* MessageQueuePanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = B91000000000000000000008; }; A20000000000000000000011 /* PromptSuggestionUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B20000000000000000000011; }; A9F000000000000000000003 = {isa = PBXBuildFile; fileRef = B9F000000000000000000003; }; A9F000000000000000000002 = {isa = PBXBuildFile; fileRef = B9F000000000000000000002; }; @@ -64,6 +65,7 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + B91000000000000000000008 /* MessageQueuePanel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageQueuePanel.swift; sourceTree = ""; }; B20000000000000000000011 /* PromptSuggestionUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptSuggestionUITests.swift; sourceTree = ""; }; B9F000000000000000000003 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarDeviceRow.swift; sourceTree = ""; }; B9F000000000000000000002 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenBitFun/Infrastructure/StartupRevealPreference.swift; sourceTree = SOURCE_ROOT; }; @@ -132,7 +134,7 @@ D10000000000000000000012 /* Remote */ = {isa = PBXGroup; children = (B10000000000000000000031 /* RemoteHomeViews.swift */); path = Remote; sourceTree = ""; }; D10000000000000000000013 /* Settings */ = {isa = PBXGroup; children = (B10000000000000000000032 /* AppSettingsView.swift */); path = Settings; sourceTree = ""; }; D10000000000000000000015 /* Account */ = {isa = PBXGroup; children = (B10000000000000000000035 /* AccountSettingsView.swift */, B10000000000000000000033 /* AccountDevicePickerSheet.swift */); path = Account; sourceTree = ""; }; - D10000000000000000000004 /* Chat */ = {isa = PBXGroup; children = (B90000000000000000000006 /* HistoryPageArrivalTracker.swift */, B90000000000000000000004 /* TimelineScrollController.swift */, B10000000000000000000030 /* ConversationHomeViews.swift */, B10000000000000000000005 /* ConversationHeader.swift */, B10000000000000000000006 /* ChatTimelineView.swift */, B10000000000000000000007 /* ComposerBar.swift */); path = Chat; sourceTree = ""; }; + D10000000000000000000004 /* Chat */ = {isa = PBXGroup; children = (B91000000000000000000008, B90000000000000000000006 /* HistoryPageArrivalTracker.swift */, B90000000000000000000004 /* TimelineScrollController.swift */, B10000000000000000000030 /* ConversationHomeViews.swift */, B10000000000000000000005 /* ConversationHeader.swift */, B10000000000000000000006 /* ChatTimelineView.swift */, B10000000000000000000007 /* ComposerBar.swift */); path = Chat; sourceTree = ""; }; D10000000000000000000005 /* Shell */ = {isa = PBXGroup; children = (B9F000000000000000000003, B9F000000000000000000001, B90000000000000000000001 /* StartupBrandReveal.swift */, B10000000000000000000003 /* OpenBitFunTheme.swift */, B10000000000000000000004 /* SidebarView.swift */, B10000000000000000000008 /* MobileShellView.swift */, B10000000000000000000019 /* SessionActionComponents.swift */, B10000000000000000000020 /* RemoteCreateSessionView.swift */, B10000000000000000000021 /* RemoteFilePreviewView.swift */, B10000000000000000000022 /* RemoteSettingsViews.swift */); path = Shell; sourceTree = ""; }; D10000000000000000000011 /* Resources */ = {isa = PBXGroup; children = (B10000000000000000000016 /* Localizable.xcstrings */); path = Resources; sourceTree = ""; }; D10000000000000000000016 /* Presentation */ = {isa = PBXGroup; children = (D10000000000000000000018 /* Models */); path = Presentation; sourceTree = ""; }; @@ -157,7 +159,7 @@ C91000000000000000000001 = {isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = (); inputPaths = (); outputPaths = ("$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/MiniApps"); alwaysOutOfDate = 1; runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "export PATH=\"/opt/homebrew/bin:/usr/local/bin:$PATH\"\nnode \"$SRCROOT/../miniapps/generate.cjs\" ios \"$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/MiniApps\"\n"; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ - C10000000000000000000002 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (A9F000000000000000000003, A9F000000000000000000002, A9F000000000000000000001, A91000000000000000000001, A90000000000000000000003, A90000000000000000000004, A90000000000000000000002, A90000000000000000000001, A10000000000000000000041, A10000000000000000000040, A10000000000000000000001, A10000000000000000000002, A10000000000000000000003, A10000000000000000000004, A10000000000000000000005, A10000000000000000000006, A10000000000000000000007, A10000000000000000000008, A10000000000000000000010, A10000000000000000000013, A10000000000000000000014, A10000000000000000000015, A10000000000000000000017, A10000000000000000000018, A10000000000000000000019, A10000000000000000000020, A10000000000000000000021, A10000000000000000000022, A10000000000000000000024, A10000000000000000000025, A10000000000000000000026, A10000000000000000000027, A10000000000000000000028, A10000000000000000000029, A10000000000000000000030, A10000000000000000000031, A10000000000000000000032, A10000000000000000000033, A10000000000000000000035, A10000000000000000000036, A10000000000000000000037, A10000000000000000000038, A90000000000000000000005, A90000000000000000000006); runOnlyForDeploymentPostprocessing = 0; }; + C10000000000000000000002 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (A91000000000000000000008, A9F000000000000000000003, A9F000000000000000000002, A9F000000000000000000001, A91000000000000000000001, A90000000000000000000003, A90000000000000000000004, A90000000000000000000002, A90000000000000000000001, A10000000000000000000041, A10000000000000000000040, A10000000000000000000001, A10000000000000000000002, A10000000000000000000003, A10000000000000000000004, A10000000000000000000005, A10000000000000000000006, A10000000000000000000007, A10000000000000000000008, A10000000000000000000010, A10000000000000000000013, A10000000000000000000014, A10000000000000000000015, A10000000000000000000017, A10000000000000000000018, A10000000000000000000019, A10000000000000000000020, A10000000000000000000021, A10000000000000000000022, A10000000000000000000024, A10000000000000000000025, A10000000000000000000026, A10000000000000000000027, A10000000000000000000028, A10000000000000000000029, A10000000000000000000030, A10000000000000000000031, A10000000000000000000032, A10000000000000000000033, A10000000000000000000035, A10000000000000000000036, A10000000000000000000037, A10000000000000000000038, A90000000000000000000005, A90000000000000000000006); runOnlyForDeploymentPostprocessing = 0; }; C20000000000000000000002 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (A20000000000000000000001 /* RemoteCodeSessionSendUITests.swift in Sources */, A20000000000000000000011 /* PromptSuggestionUITests.swift in Sources */); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ diff --git a/src/apps/mobile/ios/OpenBitFun/Features/Chat/ComposerBar.swift b/src/apps/mobile/ios/OpenBitFun/Features/Chat/ComposerBar.swift index 4afae36c67..36b6a62c6c 100644 --- a/src/apps/mobile/ios/OpenBitFun/Features/Chat/ComposerBar.swift +++ b/src/apps/mobile/ios/OpenBitFun/Features/Chat/ComposerBar.swift @@ -120,7 +120,7 @@ struct ComposerBar: View { ) .shadow(color: OpenBitFunTheme.shadowSubtle, radius: 10, y: 2) .padding(.horizontal, MobileDesignGeometry.conversationOverlaySideInset) - .padding(.top, 8) + .padding(.top, model.surface == .remote && model.messageQueue?.sessionId == model.selectedSessionID && (!(model.messageQueue?.items.isEmpty ?? true) || model.messageQueue?.failure != nil) ? 0 : 8) .padding(.bottom, 14) .animation(.easeOut(duration: 0.22), value: expanded) .animation(.easeOut(duration: 0.18), value: model.composerImages.count) diff --git a/src/apps/mobile/ios/OpenBitFun/Features/Chat/MessageQueuePanel.swift b/src/apps/mobile/ios/OpenBitFun/Features/Chat/MessageQueuePanel.swift new file mode 100644 index 0000000000..17f3f73270 --- /dev/null +++ b/src/apps/mobile/ios/OpenBitFun/Features/Chat/MessageQueuePanel.swift @@ -0,0 +1,123 @@ +import SwiftUI +import OpenBitFunMobileCore + +private struct QueueRowBounds: PreferenceKey { + static var defaultValue: [String: CGRect] = [:] + static func reduce(value: inout [String: CGRect], nextValue: () -> [String: CGRect]) { value.merge(nextValue(), uniquingKeysWith: { _, new in new }) } +} + +struct MessageQueuePanel: View { + @ObservedObject var model: MobileAppModel + @State private var expanded = true + @State private var dragging: String? + @State private var displacement: CGFloat = 0 + @State private var destination: String? + @State private var dragFrames: [String: CGRect] = [:] + @State private var dragRevision = "" + @State private var frames: [String: CGRect] = [:] + + var body: some View { + if model.surface == .remote, let queue = model.messageQueue, queue.sessionId == model.selectedSessionID, + !queue.items.isEmpty || queue.failure != nil { + VStack(alignment: .leading, spacing: 0) { + Button { expanded.toggle() } label: { + HStack(spacing: 6) { + Text(model.localizedFormat("待发送 · %d", queue.items.count)) + Image(systemName: expanded ? "chevron.down" : "chevron.up").font(.system(size: 10)) + }.font(MobileDesignTypography.bodySmall.font).frame(minHeight: 40) + }.buttonStyle(.plain).foregroundStyle(OpenBitFunTheme.muted) + if queue.failure != nil { + HStack { + Text(model.localized(queue.failure == .unsupported ? "升级执行端后可调整消息顺序。" : "队列状态已变化或未能确认,请刷新后再操作。")) + Button(model.localized("刷新")) { model.refreshMessageQueue() }.disabled(queue.busy) + }.font(MobileDesignTypography.bodySmall.font) + } + if expanded { + ScrollView { + VStack(spacing: 0) { + ForEach(queue.items, id: \.id) { item in row(item, queue: queue) } + } + }.frame(height: min(CGFloat(queue.items.count) * 48.5, 194)) + } + } + .coordinateSpace(name: "message-queue") + .onPreferenceChange(QueueRowBounds.self) { frames = $0 } + .padding(.horizontal, MobileDesignGeometry.contentGutter) + .onChange(of: queue.revisionKey) { _ in cancelDrag() } + .onChange(of: queue.failure) { _ in cancelDrag() } + .onChange(of: queue.busy) { _ in cancelDrag() } + .onChange(of: model.selectedSessionID) { _ in cancelDrag(); expanded = true } + .onDisappear { cancelDrag() } + } + } + + private func cancelDrag() { dragging = nil; displacement = 0; destination = nil } + private func row(_ item: QueuedMessageUiState, queue: MessageQueueUiState) -> some View { + let ids = queue.items.filter { $0.status == "queued" }.map { $0.id } + let index = ids.firstIndex(of: item.id) + let enabled = queue.supportsReorder && !queue.busy && queue.failure == nil && index != nil + return VStack(spacing: 0) { + Rectangle().fill(OpenBitFunTheme.line).frame(height: 0.5).padding(.horizontal, 8) + HStack(alignment: .top, spacing: 4) { + if queue.supportsReorder { + Image(systemName: "line.3.horizontal").font(.system(size: 14)).foregroundStyle(OpenBitFunTheme.muted) + .frame(width: 44, height: 48).contentShape(Rectangle()) + .accessibilityLabel(model.localized("拖动排序")) + .gesture(DragGesture(minimumDistance: 6, coordinateSpace: .named("message-queue")) + .onChanged { value in + guard enabled, ids.count > 1 else { return } + if dragging == nil { dragging = item.id; dragFrames = frames; dragRevision = queue.revisionKey } + displacement = value.translation.height + let center = (dragFrames[item.id]?.midY ?? value.startLocation.y) + displacement + destination = ids.first { $0 != item.id && center < (dragFrames[$0]?.midY ?? .greatestFiniteMagnitude) } + } + .onEnded { _ in + if dragging == item.id, dragRevision == model.messageQueue?.revisionKey, let index, destination != ids.dropFirst(index + 1).first { + model.moveQueuedMessage(item.id, before: destination) + } + cancelDrag() + }) + } + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 6) { + Text(item.text).lineLimit(1).truncationMode(.tail) + if item.attachmentCount > 0 { + Label("\(item.attachmentCount)", systemImage: "paperclip").font(MobileDesignTypography.bodySmall.font) + .foregroundStyle(OpenBitFunTheme.muted).fixedSize() + } + } + if item.status != "queued" { Text(model.localized("等待执行端处理")).font(MobileDesignTypography.bodySmall.font).foregroundStyle(OpenBitFunTheme.muted) } + }.font(MobileDesignTypography.bodyMedium.font).frame(maxWidth: .infinity, minHeight: 48, alignment: .leading) + Button { model.promoteQueuedMessage(item.id) } label: { + Image(systemName: "arrow.turn.down.right").frame(width: 44, height: 48) + }.disabled(queue.busy || queue.failure != nil || !["queued", "blocked"].contains(item.status)) + .accessibilityLabel(model.localized("立即发送")) + Menu { + Text(item.text) + if !queue.supportsReorder { Text(model.localized("升级执行端后可调整消息顺序。")) } + Button(model.localized("上移")) { if let index, index > 0 { model.moveQueuedMessage(item.id, before: ids[index - 1]) } }.disabled(!enabled || index == 0) + Button(model.localized("下移")) { if let index { model.moveQueuedMessage(item.id, before: ids.dropFirst(index + 2).first) } }.disabled(!enabled || index == ids.count - 1) + Button(model.localized("从队列移除"), role: .destructive) { model.cancelQueuedMessage(item.id) } + .disabled(queue.busy || queue.failure != nil || !["queued", "blocked"].contains(item.status)) + } label: { Image(systemName: "ellipsis").frame(width: 44, height: 48) } + .accessibilityLabel(model.localized("消息操作")) + }.buttonStyle(.plain).foregroundStyle(OpenBitFunTheme.ink) + } + .overlay(alignment: .top) { + if dragging != nil && destination == item.id { + Rectangle().fill(OpenBitFunTheme.accent).frame(height: 1) + } + } + .overlay(alignment: .bottom) { + if dragging != nil && destination == nil && item.id == ids.last(where: { $0 != dragging }) { + Rectangle().fill(OpenBitFunTheme.accent).frame(height: 1) + } + } + .background(dragging == item.id ? OpenBitFunTheme.card : Color.clear) + .background(GeometryReader { proxy in Color.clear.preference(key: QueueRowBounds.self, value: [item.id: proxy.frame(in: .named("message-queue"))]) }) + .offset(y: dragging == item.id ? displacement : 0) + .zIndex(dragging == item.id ? 1 : 0) + .accessibilityAction(named: Text(model.localized("上移"))) { if enabled, let index, index > 0 { model.moveQueuedMessage(item.id, before: ids[index - 1]) } } + .accessibilityAction(named: Text(model.localized("下移"))) { if enabled, let index, index < ids.count - 1 { model.moveQueuedMessage(item.id, before: ids.dropFirst(index + 2).first) } } + } +} diff --git a/src/apps/mobile/ios/OpenBitFun/Features/Shell/MobileShellView.swift b/src/apps/mobile/ios/OpenBitFun/Features/Shell/MobileShellView.swift index d1ce9f1074..1c40e5142e 100644 --- a/src/apps/mobile/ios/OpenBitFun/Features/Shell/MobileShellView.swift +++ b/src/apps/mobile/ios/OpenBitFun/Features/Shell/MobileShellView.swift @@ -398,6 +398,7 @@ struct MobileShellView: View { } .safeAreaInset(edge: .bottom, spacing: 0) { VStack(spacing: 0) { + MessageQueuePanel(model: model) ComposerBar(model: model) } // The fade covers the whole layer, not just a strip above it: the diff --git a/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+RemoteSession.swift b/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+RemoteSession.swift index 92b323eae9..86ee58a992 100644 --- a/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+RemoteSession.swift +++ b/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel+RemoteSession.swift @@ -1000,6 +1000,11 @@ extension MobileAppModel { ) } + func refreshMessageQueue() { coreAdapter?.refreshMessageQueue() } + func moveQueuedMessage(_ id: String, before: String?) { coreAdapter?.moveQueuedMessage(id, before: before) } + func cancelQueuedMessage(_ id: String) { coreAdapter?.cancelQueuedMessage(id) } + func promoteQueuedMessage(_ id: String) { coreAdapter?.promoteQueuedMessage(id) } + func apply(remoteState state: RemoteSessionUiState, targetKey: String, epoch: UInt64) { guard !localActionPreview, !accountLoginPreview, !remoteCreatePreview else { return } guard RemoteAuthorityGate.callbackMatchesAuthority( @@ -1020,6 +1025,7 @@ extension MobileAppModel { return } permissionMailbox = nil + messageQueue = nil remoteOpenedSessionID = nil remoteInitialSessionReady = false if let failed = state as? RemoteSessionUiStateFailed { @@ -1062,6 +1068,7 @@ extension MobileAppModel { ) else { return } setPublishedIfChanged(\.remoteOpenedSessionID, to: ready.timeline?.sessionId) permissionMailbox = ready.permissionMailbox + messageQueue = ready.messageQueue completionNotifier.observe(state, target: "\(targetKey):\(epoch)") remoteLastAppliedAuthority = RemoteAuthorityGate.updatedScope( targetKey: targetKey, diff --git a/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel.swift b/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel.swift index 1fa41e05e7..dfc4a9f1af 100644 --- a/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel.swift +++ b/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileAppModel.swift @@ -26,6 +26,7 @@ final class MobileAppModel: ObservableObject { /// transcript: a reopened session shows them at once, and the host has not /// answered for it yet. See `ChatTranscriptOrigin`. @Published var remoteTranscriptUnconfirmed = false + @Published var messageQueue: MessageQueueUiState? @Published var permissionMailbox: PermissionMailboxUiState? @Published var remoteConversationLoading = false @Published var remotePermissionMode = "ASK" diff --git a/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileCoreAdapter.swift b/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileCoreAdapter.swift index d177037a28..11d706cb8a 100644 --- a/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileCoreAdapter.swift +++ b/src/apps/mobile/ios/OpenBitFun/Infrastructure/MobileCoreAdapter.swift @@ -319,6 +319,11 @@ final class MobileCoreAdapter { ) } + func refreshMessageQueue() { remoteSession?.dispatch(intent: RemoteSessionIntentRefreshMessageQueue.shared) } + func moveQueuedMessage(_ id: String, before: String?) { remoteSession?.dispatch(intent: RemoteSessionIntentMoveQueuedMessage(id: id, beforeId: before)) } + func cancelQueuedMessage(_ id: String) { remoteSession?.dispatch(intent: RemoteSessionIntentCancelQueuedMessage(id: id)) } + func promoteQueuedMessage(_ id: String) { remoteSession?.dispatch(intent: RemoteSessionIntentPromoteQueuedMessage(id: id)) } + func renameRemoteSession(sessionID: String, title: String) { remoteSession?.dispatch( intent: RemoteSessionIntentRenameSession(sessionId: sessionID, title: title) diff --git a/src/apps/mobile/ios/OpenBitFun/Resources/Localizable.xcstrings b/src/apps/mobile/ios/OpenBitFun/Resources/Localizable.xcstrings index c19c7fe866..5519d31857 100644 --- a/src/apps/mobile/ios/OpenBitFun/Resources/Localizable.xcstrings +++ b/src/apps/mobile/ios/OpenBitFun/Resources/Localizable.xcstrings @@ -3,8 +3,18 @@ "strings": { "填入输入框": { "localizations": { - "en": { "stringUnit": { "state": "translated", "value": "Use suggestion" } }, - "zh-Hans": { "stringUnit": { "state": "translated", "value": "填入输入框" } } + "en": { + "stringUnit": { + "state": "translated", + "value": "Use suggestion" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "填入输入框" + } + } } }, "旧版设备:显示最近访问的工作区": { @@ -8318,6 +8328,166 @@ } } } + }, + "待发送 · %d": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Queued messages · %d" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "待发送 · %d" + } + } + } + }, + "拖动排序": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Drag to reorder" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "拖动排序" + } + } + } + }, + "上移": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Move up" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "上移" + } + } + } + }, + "下移": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Move down" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "下移" + } + } + } + }, + "队列状态已变化或未能确认,请刷新后再操作。": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Queue status changed or could not be confirmed. Refresh before another action." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "队列状态已变化或未能确认,请刷新后再操作。" + } + } + } + }, + "等待执行端处理": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Waiting for the execution host" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "等待执行端处理" + } + } + } + }, + "立即发送": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Send now" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "立即发送" + } + } + } + }, + "从队列移除": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Remove from queue" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "从队列移除" + } + } + } + }, + "消息操作": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Message actions" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "消息操作" + } + } + } + }, + "升级执行端后可调整消息顺序。": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Update the execution host to reorder messages." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "升级执行端后可调整消息顺序。" + } + } + } } }, "version": "1.0" diff --git a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/MessageQueueStore.kt b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/MessageQueueStore.kt new file mode 100644 index 0000000000..9624032106 --- /dev/null +++ b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/MessageQueueStore.kt @@ -0,0 +1,119 @@ +package com.openbitfun.mobile.core.feature.session + +import com.openbitfun.mobile.core.protocol.DialogQueueRequest +import com.openbitfun.mobile.core.protocol.DialogQueueResponse +import com.openbitfun.mobile.core.protocol.DialogQueueSnapshot +import com.openbitfun.mobile.core.protocol.RemoteCommand +import com.openbitfun.mobile.core.protocol.isError +import com.openbitfun.mobile.core.transport.RemoteCommandTransport +import com.openbitfun.mobile.core.transport.send +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlin.time.Clock + +public data class QueuedMessageUiState public constructor( + public val id: String, public val text: String, public val attachmentCount: Int, + public val status: String, public val reason: String?, +) +public enum class MessageQueueFailure { LOAD, CONFLICT, OUTCOME_UNKNOWN, UNSUPPORTED } +public data class MessageQueueUiState public constructor( + public val sessionId: String?, public val supported: Boolean, public val supportsReorder: Boolean, + public val revisionKey: String, public val items: List, public val busy: Boolean, public val failure: MessageQueueFailure?, +) { + public constructor() : this(null, false, false, "", emptyList(), false, null) +} + +/** Reads the execution host's queue. Mutations are never replayed after an ambiguous reply. */ +internal class MessageQueueStore(private val scope: CoroutineScope, private val transport: RemoteCommandTransport, + private val publish: (MessageQueueUiState) -> Unit) { + private var state = MessageQueueUiState() + private var snapshot: DialogQueueSnapshot? = null + private var generation = 0L + private var foreground = true + private var reader: Job? = null + private var mutation: Job? = null + private val mutex = Mutex() + private fun update(next: MessageQueueUiState) { state = next; publish(next) } + fun select(sessionId: String?, supported: Boolean) { + if (state.sessionId == sessionId && state.supported == supported) return + generation++ + reader?.cancel(); mutation?.cancel(); snapshot = null + val retained = state.items.takeIf { state.sessionId == sessionId }.orEmpty() + update(MessageQueueUiState(sessionId, supported, false, "", retained, false, + MessageQueueFailure.UNSUPPORTED.takeIf { !supported && retained.isNotEmpty() })) + restartReader() + } + fun setForeground(active: Boolean) { foreground = active; restartReader() } + private fun restartReader() { + reader?.cancel(); reader = null + if (!foreground || !state.supported || state.sessionId == null) return + val ticket = generation + reader = scope.launch { + while (ticket == generation) { + refresh() + delay(if (state.items.isEmpty()) 10_000 else 2_000) + } + } + } + fun invalidate() { restartReader() } + private suspend fun invoke(request: DialogQueueRequest): DialogQueueSnapshot { + val response = transport.send(RemoteCommand(cmd = "dialog_queue", request = request)) + check(!response.isError) { response.message ?: "Queue request failed" } + val value = checkNotNull(response.snapshot) { "Missing queue snapshot" } + check(value.sessionId == request.sessionId && value.queueEpoch.isNotBlank()) { "Invalid queue scope" } + return value + } + private fun accept(value: DialogQueueSnapshot, authoritative: Boolean) { + val previous = snapshot + if (previous != null && (value.queueEpoch != previous.queueEpoch && !authoritative || + value.queueEpoch == previous.queueEpoch && value.revision < previous.revision)) return + snapshot = value + update(state.copy(supportsReorder = value.supportsReorder, failure = null, revisionKey = "${value.queueEpoch}:${value.revision}", + items = value.items.map { QueuedMessageUiState(it.turnId, it.displayContent, it.attachmentCount, it.status, it.reason) })) + } + private suspend fun refresh() { + val selected = state.sessionId ?: return + val ticket = generation + try { + mutex.withLock { + val value = invoke(DialogQueueRequest(selected, "list")) + if (ticket == generation) accept(value, true) + } + } catch (cancelled: CancellationException) { throw cancelled } + catch (_: Throwable) { if (ticket == generation) update(state.copy(failure = MessageQueueFailure.LOAD)) } + } + fun move(id: String, beforeId: String?) = act(id, "reorder", beforeId) + fun act(id: String, action: String, beforeId: String? = null) { + val observed = snapshot ?: return + if (state.busy || state.failure != null || !state.supported || !foreground) return + val item = state.items.find { it.id == id } ?: return + if (item.status !in listOf("queued", "blocked")) return + if (action == "reorder" && (!observed.supportsReorder || item.status != "queued")) { + update(state.copy(failure = MessageQueueFailure.UNSUPPORTED)); return + } + val ticket = generation + val operationId = "mobile-queue-${Clock.System.now().toEpochMilliseconds()}-${kotlin.random.Random.nextLong().toULong()}" + update(state.copy(busy = true)) + mutation = scope.launch { + try { + mutex.withLock { + val value = invoke(DialogQueueRequest(observed.sessionId, action, observed.queueEpoch, id, operationId, + beforeId, observed.revision.takeIf { action == "reorder" }, observed.activeTurnId)) + if (ticket == generation) { + check(value.queueEpoch == observed.queueEpoch) { "queue_conflict: queue owner changed" } + accept(value, false) + } + } + } catch (cancelled: CancellationException) { throw cancelled } + catch (error: Throwable) { + if (ticket == generation) update(state.copy(failure = if (error.message?.contains("queue_conflict:") == true || + error.message?.contains("too_late:") == true) MessageQueueFailure.CONFLICT else MessageQueueFailure.OUTCOME_UNKNOWN)) + } finally { if (ticket == generation) update(state.copy(busy = false)) } + } + } +} diff --git a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStore.kt b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStore.kt index f0ed846413..111aad7c8d 100644 --- a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStore.kt +++ b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionStore.kt @@ -164,6 +164,10 @@ public class RemoteSessionStore internal constructor( private var modelCatalogDirty = false private var permissionRefresh: Job? = null private val timelineStore = ChatTimelineStore() + private val messageQueue = MessageQueueStore(scope, transport) { queue -> + val ready = _state.value as? RemoteSessionUiState.Ready + if (ready != null && ready.selectedSessionId == queue.sessionId) _state.value = ready.copy(messageQueue = queue) + } private val permissionMailbox = PermissionMailboxStore(scope, transport) { mailbox -> val ready = _state.value as? RemoteSessionUiState.Ready if (ready != null) _state.value = ready.copy(permissionMailbox = mailbox) @@ -216,6 +220,10 @@ public class RemoteSessionStore internal constructor( public fun dispatch(intent: RemoteSessionIntent) { val current = _state.value as? RemoteSessionUiState.Ready when (intent) { + RemoteSessionIntent.RefreshMessageQueue -> messageQueue.invalidate() + is RemoteSessionIntent.MoveQueuedMessage -> messageQueue.move(intent.id, intent.beforeId) + is RemoteSessionIntent.CancelQueuedMessage -> messageQueue.act(intent.id, "cancel") + is RemoteSessionIntent.PromoteQueuedMessage -> messageQueue.act(intent.id, "promote") is RemoteSessionIntent.StartQuestionInteraction -> permissionMailbox.startQuestion(intent.toolId) is RemoteSessionIntent.RespondPermission -> permissionMailbox.respond(intent.requestId, intent.approve, intent.updatedInput) RemoteSessionIntent.RefreshPermissionMailbox -> permissionMailbox.invalidate() @@ -632,6 +640,7 @@ public class RemoteSessionStore internal constructor( (_state.value as? RemoteSessionUiState.Ready)?.let { _state.value = it.copy(promptSuggestion = null) } catalogSubscription?.cancel(); catalogRefresh?.cancel() permissionMailbox.select(null) + messageQueue.select(null, false) setForeground(false) activeCreateGeneration?.let { generation -> val requestId = (_createOperation.value as? CreateSessionOperationState.InFlight)?.requestId @@ -799,6 +808,7 @@ public class RemoteSessionStore internal constructor( private fun recordHostCapabilities(capabilities: List) { hostCapabilities = capabilities + messageQueue.select((_state.value as? RemoteSessionUiState.Ready)?.selectedSessionId, "dialog_queue_v1" in capabilities) hostCapabilitiesKnown = true } @@ -1095,6 +1105,7 @@ public class RemoteSessionStore internal constructor( private fun subscribeSessionUpdates(sessionId: String): CompletableDeferred { val initialHistory = CompletableDeferred() permissionMailbox.select(sessionId) + messageQueue.select(sessionId, "dialog_queue_v1" in hostCapabilities) sessionUpdates?.cancel() transcriptWrite?.cancel() forgetWrittenTranscript() @@ -2205,6 +2216,7 @@ public class RemoteSessionStore internal constructor( /** Relay replay proves log availability, not that the controlled host is online. * Keep foreground host probes for idle open conversations as well as lists. */ private fun setForeground(active: Boolean) { + messageQueue.setForeground(active) if (active && healthWork?.isActive == true) return val generation = ++healthGeneration healthWork?.cancel() diff --git a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionUiState.kt b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionUiState.kt index ba3f8b8622..82d9b5ae27 100644 --- a/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionUiState.kt +++ b/src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/session/RemoteSessionUiState.kt @@ -296,7 +296,18 @@ public sealed interface RemoteSessionUiState { public val historyLoadState: HistoryLoadState, /** Host hint for the latest completed turn; never persisted with the transcript. */ public val promptSuggestion: String?, + public val messageQueue: MessageQueueUiState, ) : RemoteSessionUiState { + public constructor( + sessions: List, selectedSessionId: String?, timeline: ChatTimelineState?, busy: Boolean, + permissionMode: SessionPermissionMode?, permissionModeFailure: PermissionModeFailure?, query: String, + agentFilter: SessionAgentFilter, hasMore: Boolean, hasMoreMessages: Boolean, + modelCatalog: RemoteModelCatalog?, modelCatalogFailure: ModelCatalogFailure?, draft: String, + revision: Long, lastSentMessage: SentChatMessage?, permissionMailbox: PermissionMailboxUiState, + historyLoadState: HistoryLoadState, promptSuggestion: String?, + ) : this(sessions, selectedSessionId, timeline, busy, permissionMode, permissionModeFailure, query, + agentFilter, hasMore, hasMoreMessages, modelCatalog, modelCatalogFailure, draft, revision, + lastSentMessage, permissionMailbox, historyLoadState, promptSuggestion, MessageQueueUiState()) /** Preserve the existing Swift initializer when adding the optional host hint. */ public constructor( sessions: List, selectedSessionId: String?, timeline: ChatTimelineState?, busy: Boolean, @@ -409,6 +420,10 @@ public sealed interface RemoteSessionUiState { } public sealed interface RemoteSessionIntent { + public data object RefreshMessageQueue : RemoteSessionIntent + public data class MoveQueuedMessage(public val id: String, public val beforeId: String?) : RemoteSessionIntent + public data class CancelQueuedMessage(public val id: String) : RemoteSessionIntent + public data class PromoteQueuedMessage(public val id: String) : RemoteSessionIntent public data class StartQuestionInteraction(public val toolId: String) : RemoteSessionIntent public data class RespondPermission(public val requestId: String, public val approve: Boolean, public val updatedInput: String?) : RemoteSessionIntent public data object RefreshPermissionMailbox : RemoteSessionIntent diff --git a/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/MessageQueueStoreTest.kt b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/MessageQueueStoreTest.kt new file mode 100644 index 0000000000..a935e4a259 --- /dev/null +++ b/src/apps/mobile/shared/core-feature/src/commonTest/kotlin/com/openbitfun/mobile/core/feature/session/MessageQueueStoreTest.kt @@ -0,0 +1,122 @@ +package com.openbitfun.mobile.core.feature.session + +import com.openbitfun.mobile.core.protocol.* +import com.openbitfun.mobile.core.transport.* +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.test.* +import kotlinx.serialization.DeserializationStrategy +import kotlin.test.* + +@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) +class MessageQueueStoreTest { + @Test fun legacySnapshotsRetainRowsAndDoNotSendUnsupportedReorder() = runTest { + val host = Host().apply { supportsReorder = false } + var state = MessageQueueUiState() + val store = MessageQueueStore(backgroundScope, host) { state = it } + store.select("session", true); runCurrent() + assertEquals(listOf("a", "b"), state.items.map { it.id }) + assertFalse(state.supportsReorder) + store.move("b", "a"); runCurrent() + assertEquals(MessageQueueFailure.UNSUPPORTED, state.failure) + assertEquals(listOf("list"), host.requests.map { it.action }) + } + + @Test fun mutationUsesObservedEpochRevisionAndDoesNotOptimisticallyReorder() = runTest { + val host = Host() + var state = MessageQueueUiState() + val store = MessageQueueStore(backgroundScope, host) { state = it } + store.select("session", true); runCurrent() + host.gate = CompletableDeferred() + store.move("b", "a"); runCurrent() + assertTrue(state.busy) + assertEquals(listOf("a", "b"), state.items.map { it.id }) + val move = host.requests.last() + assertEquals("reorder", move.action) + assertEquals("epoch", move.queueEpoch) + assertEquals(7, move.expectedRevision) + assertEquals("a", move.beforeTurnId) + assertNotNull(move.operationId) + host.gate!!.complete(Unit); runCurrent() + assertFalse(state.busy) + assertEquals(listOf("b", "a"), state.items.map { it.id }) + assertEquals("epoch:8", state.revisionKey) + } + + @Test fun lostMutationReplyKeepsRowsAndCannotAutomaticallyResubmit() = runTest { + val host = Host() + var state = MessageQueueUiState() + val store = MessageQueueStore(backgroundScope, host) { state = it } + store.select("session", true); runCurrent() + host.failMutation = true + store.move("b", "a"); runCurrent() + assertEquals(MessageQueueFailure.OUTCOME_UNKNOWN, state.failure) + assertEquals(listOf("a", "b"), state.items.map { it.id }) + store.move("b", "a"); runCurrent() + assertEquals(1, host.requests.count { it.action == "reorder" }) + store.invalidate(); runCurrent() + assertNull(state.failure) + assertEquals(listOf("b", "a"), state.items.map { it.id }) + assertEquals(1, host.requests.count { it.action == "reorder" }) + } + + @Test fun changingSessionDuringMutationCannotPublishOldRows() = runTest { + val host = Host() + var state = MessageQueueUiState() + val store = MessageQueueStore(backgroundScope, host) { state = it } + store.select("session", true); runCurrent() + host.gate = CompletableDeferred() + store.move("b", "a"); runCurrent() + store.select("another", true); runCurrent() + host.gate!!.complete(Unit); runCurrent() + assertEquals("another", state.sessionId) + assertFalse(state.busy) + assertEquals(listOf("other"), state.items.map { it.id }) + } + + @Test fun losingHostCapabilityRetainsTheVisibleMessages() = runTest { + val host = Host() + var state = MessageQueueUiState() + val store = MessageQueueStore(backgroundScope, host) { state = it } + store.select("session", true); runCurrent() + store.select("session", false); runCurrent() + assertEquals(listOf("a", "b"), state.items.map { it.id }) + assertEquals(MessageQueueFailure.UNSUPPORTED, state.failure) + assertFalse(state.supported) + } + + @Test fun backgroundAndUnsupportedHostDoNotPoll() = runTest { + val host = Host() + val store = MessageQueueStore(backgroundScope, host) {} + store.select("session", false); runCurrent() + assertTrue(host.requests.isEmpty()) + store.setForeground(false); store.select("session", true); runCurrent() + assertTrue(host.requests.isEmpty()) + store.setForeground(true); runCurrent() + assertEquals(1, host.requests.size) + store.select(null, false); advanceTimeBy(20_000); runCurrent() + assertEquals(1, host.requests.size) + } + + private class Host : RemoteCommandTransport { + val requests = mutableListOf() + var supportsReorder = true + var order = listOf("a", "b") + var revision = 7 + var gate: CompletableDeferred? = null + var failMutation = false + override suspend fun send(deserializer: DeserializationStrategy, command: RemoteCommand, timeoutMs: Long): T { + val request = requireNotNull(command.request) + requests += request + if (request.action == "reorder") { + gate?.await() + order = listOf("b", "a"); revision++ + if (failMutation) error("Connection lost after acceptance") + } + val items = (if (request.sessionId == "another") listOf("other") else order).joinToString(",") { + """{"turnId":"$it","displayContent":"$it","status":"queued","futureField":true}""" + } + val capability = if (supportsReorder) ",\"supportsReorder\":true" else "" + return RelayJson.decodeFromString(deserializer, """{"resp":"dialog_queue_result","snapshot":{"sessionId":"${request.sessionId}","queueEpoch":"epoch","revision":$revision,"items":[$items]$capability}}""") + } + } +} diff --git a/src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/DialogQueue.kt b/src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/DialogQueue.kt new file mode 100644 index 0000000000..0844434350 --- /dev/null +++ b/src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/DialogQueue.kt @@ -0,0 +1,41 @@ +package com.openbitfun.mobile.core.protocol + +import kotlinx.serialization.Serializable + +@Serializable +public data class DialogQueueRequest( + val sessionId: String, + val action: String, + val queueEpoch: String? = null, + val turnId: String? = null, + val operationId: String? = null, + val beforeTurnId: String? = null, + val expectedRevision: Long? = null, + val expectedActiveTurnId: String? = null, +) + +@Serializable +public data class DialogQueueItem( + val turnId: String, + val displayContent: String, + val status: String, + val attachmentCount: Int = 0, + val reason: String? = null, +) + +@Serializable +public data class DialogQueueSnapshot( + val sessionId: String, + val queueEpoch: String, + val revision: Long, + val items: List = emptyList(), + val supportsReorder: Boolean = false, + val activeTurnId: String? = null, +) + +@Serializable +public data class DialogQueueResponse( + override val resp: String? = null, + override val message: String? = null, + val snapshot: DialogQueueSnapshot? = null, +) : CommandStatus diff --git a/src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/RemoteCommand.kt b/src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/RemoteCommand.kt index 1bc276b4fc..261d0cc605 100644 --- a/src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/RemoteCommand.kt +++ b/src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/RemoteCommand.kt @@ -56,6 +56,7 @@ public object RemotePermissionModeSerializer : KSerializer @Serializable public data class RemoteCommand( @SerialName("cmd") val cmd: String, + @SerialName("request") val request: DialogQueueRequest? = null, @SerialName("command") val command: String? = null, @SerialName("args") val args: JsonElement? = null, @SerialName("_request_id") val requestId: String? = null, diff --git a/src/crates/assembly/core/src/agentic/coordination/host_message_queue.rs b/src/crates/assembly/core/src/agentic/coordination/host_message_queue.rs index 4dcd5f723e..35ff4981ea 100644 --- a/src/crates/assembly/core/src/agentic/coordination/host_message_queue.rs +++ b/src/crates/assembly/core/src/agentic/coordination/host_message_queue.rs @@ -337,6 +337,7 @@ impl DialogScheduler { revision: s.revision, active_turn_id, items, + supports_reorder: Some(true), capacity: self.queues.max_depth(), used: self.queues.depth(session) + held, receipt: receipt_id @@ -532,6 +533,11 @@ impl DialogScheduler { turn_id, operation_id, } + | DialogQueueAction::Reorder { + turn_id, + operation_id, + .. + } | DialogQueueAction::Promote { turn_id, operation_id, @@ -570,6 +576,67 @@ impl DialogScheduler { )); } } + if let DialogQueueAction::Reorder { + before_turn_id, + expected_revision, + .. + } = &action + { + let snapshot = self.queue_snapshot(session, None); + if snapshot.revision != *expected_revision { + return Err(error( + "queue_conflict: queue changed; refresh before reordering", + )); + } + let mut order: Vec<_> = snapshot + .items + .iter() + .filter(|item| item.status == DialogQueueStatus::Queued) + .map(|item| item.turn_id.clone()) + .collect(); + let Some(from) = order.iter().position(|turn| turn == &id) else { + return Err(error("too_late: only queued messages can be reordered")); + }; + if before_turn_id.as_ref() == Some(&id) { + return Err(error( + "queue_conflict: a message cannot be moved before itself", + )); + } + order.remove(from); + let to = if let Some(before) = before_turn_id { + order + .iter() + .position(|turn| turn == before) + .ok_or_else(|| error("queue_conflict: destination is no longer queued"))? + } else { + order.len() + }; + order.insert(to, id.clone()); + if !self + .queues + .reorder_subset(session, &order, |turn| turn.turn_id.as_deref()) + { + return Err(error("queue_conflict: dispatch queue changed")); + } + // Match the actual dispatch order while preserving fixed steering, + // blocked and terminal receipt slots. Never resubmit accepted work. + let mut state = self.queue_state(); + let s = state.sessions.get_mut(session).unwrap(); + let positions: Vec<_> = s + .order + .iter() + .enumerate() + .filter(|(_, turn)| order.contains(turn)) + .map(|(index, _)| index) + .collect(); + for (position, turn) in positions.into_iter().zip(order) { + s.order[position] = turn; + } + s.operations.insert(operation, (digest, id.clone())); + s.revision += 1; + drop(state); + return Ok(self.queue_snapshot(session, Some(&id))); + } let mut interrupted_turn_to_abandon = None; if let DialogQueueAction::Promote { expected_active_turn_id, diff --git a/src/crates/assembly/core/src/agentic/coordination/host_message_queue_tests.rs b/src/crates/assembly/core/src/agentic/coordination/host_message_queue_tests.rs index 8d8530ffcc..40256dffe4 100644 --- a/src/crates/assembly/core/src/agentic/coordination/host_message_queue_tests.rs +++ b/src/crates/assembly/core/src/agentic/coordination/host_message_queue_tests.rs @@ -1599,3 +1599,109 @@ async fn host_queue_handoff_preserves_turn_scoped_sdk_steering() { ); assert!(!scheduler.queues.has_items("host-queue-session")); } + +#[tokio::test] +async fn host_queue_reorder_changes_dispatch_order_and_retries_exactly_once() { + let (scheduler, _sessions, _root, epoch) = fixture().await; + let mut snapshot = scheduler + .manage_host_queue(request(None, Action::List)) + .await + .unwrap(); + assert_eq!(snapshot.supports_reorder, Some(true)); + for id in ["first", "second", "third"] { + snapshot = scheduler + .manage_host_queue(request( + Some(&epoch), + Action::Submit { + message: message(id), + }, + )) + .await + .unwrap(); + } + let reorder = Action::Reorder { + turn_id: "third".into(), + before_turn_id: Some("first".into()), + operation_id: "move-third".into(), + expected_revision: snapshot.revision, + }; + let moved = scheduler + .manage_host_queue(request(Some(&epoch), reorder.clone())) + .await + .unwrap(); + assert_eq!( + moved + .items + .iter() + .map(|item| item.turn_id.as_str()) + .collect::>(), + ["third", "first", "second"] + ); + let replay = scheduler + .manage_host_queue(request(Some(&epoch), reorder)) + .await + .unwrap(); + assert_eq!(replay.revision, moved.revision); + let stale = scheduler + .manage_host_queue(request( + Some(&epoch), + Action::Reorder { + turn_id: "second".into(), + before_turn_id: None, + operation_id: "stale".into(), + expected_revision: snapshot.revision, + }, + )) + .await + .unwrap_err(); + assert!(stale.message.contains("queue_conflict:")); + for expected in ["third", "first", "second"] { + assert_eq!( + scheduler + .queues + .dequeue_next("host-queue-session") + .unwrap() + .turn_id + .as_deref(), + Some(expected) + ); + } +} + +#[tokio::test] +async fn host_queue_reorder_rejects_invalid_targets_without_losing_work() { + let (scheduler, _sessions, _root, epoch) = fixture().await; + let snapshot = scheduler + .manage_host_queue(request( + Some(&epoch), + Action::Submit { + message: message("only"), + }, + )) + .await + .unwrap(); + for before in ["missing", "only"] { + let failure = scheduler + .manage_host_queue(request( + Some(&epoch), + Action::Reorder { + turn_id: "only".into(), + before_turn_id: Some(before.into()), + operation_id: before.into(), + expected_revision: snapshot.revision, + }, + )) + .await + .unwrap_err(); + assert!(failure.message.contains("queue_conflict:")); + } + assert_eq!( + scheduler + .queues + .dequeue_next("host-queue-session") + .unwrap() + .turn_id + .as_deref(), + Some("only") + ); +} diff --git a/src/crates/contracts/runtime-ports/src/dialog_queue.rs b/src/crates/contracts/runtime-ports/src/dialog_queue.rs index b9c4e2e7a0..1f73009305 100644 --- a/src/crates/contracts/runtime-ports/src/dialog_queue.rs +++ b/src/crates/contracts/runtime-ports/src/dialog_queue.rs @@ -34,6 +34,14 @@ pub enum DialogQueueAction { turn_id: String, operation_id: String, }, + /// Move a queued message before another queued message (None means last). + /// Clients must negotiate supportsReorder from a fresh snapshot first. + Reorder { + turn_id: String, + before_turn_id: Option, + operation_id: String, + expected_revision: u64, + }, Promote { turn_id: String, operation_id: String, @@ -107,6 +115,9 @@ pub struct DialogQueueSnapshot { pub revision: u64, pub active_turn_id: Option, pub items: Vec, + /// Absent on hosts predating reorder; never infer support from version. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub supports_reorder: Option, pub capacity: usize, pub used: usize, /// Present for submission queries and mutations; terminal receipts remain queryable. @@ -117,6 +128,19 @@ pub struct DialogQueueSnapshot { mod tests { use super::*; + #[test] + fn legacy_snapshot_and_reorder_negotiation_round_trip() { + let legacy = serde_json::json!({"sessionId":"session", "queueEpoch":"owner", "revision":2, + "activeTurnId":null, "items":[], "capacity":10, "used":0, "receipt":null}); + let snapshot: DialogQueueSnapshot = serde_json::from_value(legacy.clone()).unwrap(); + assert_eq!(snapshot.supports_reorder, None); + assert_eq!(serde_json::to_value(snapshot).unwrap(), legacy); + let input = serde_json::json!({"sessionId":"session", "queueEpoch":"owner", "action":"reorder", + "turnId":"last", "beforeTurnId":"first", "operationId":"move", "expectedRevision":2}); + let request: DialogQueueRequest = serde_json::from_value(input.clone()).unwrap(); + assert_eq!(serde_json::to_value(request).unwrap(), input); + } + #[test] fn queue_request_wire_defaults_and_extensions_are_compatible() { let legacy = serde_json::json!({"sessionId":"session", "action":"list"}); diff --git a/src/crates/execution/agent-runtime/src/scheduler.rs b/src/crates/execution/agent-runtime/src/scheduler.rs index 5b3a734195..6dfeefaf57 100644 --- a/src/crates/execution/agent-runtime/src/scheduler.rs +++ b/src/crates/execution/agent-runtime/src/scheduler.rs @@ -355,6 +355,48 @@ impl DialogTurnQueue { turn } + /// Reorder an exact subset without disturbing other work or priority lanes. + /// Validate the entire permutation before touching the queue. + pub fn reorder_subset(&self, session_id: &str, ids: &[String], identify: F) -> bool + where + T: Clone, + F: Fn(&T) -> Option<&str>, + { + let Some(mut queue) = self.inner.get_mut(session_id) else { + return false; + }; + let mut positions = Vec::with_capacity(ids.len()); + for id in ids { + let Some(position) = queue + .iter() + .position(|entry| identify(&entry.turn) == Some(id.as_str())) + else { + return false; + }; + if positions.contains(&position) { + return false; + } + positions.push(position); + } + if let Some(&first) = positions.first() { + if positions + .iter() + .any(|&position| queue[position].priority != queue[first].priority) + { + return false; + } + } + let turns: Vec<_> = positions + .iter() + .map(|&position| queue[position].turn.clone()) + .collect(); + positions.sort_unstable(); + for (position, turn) in positions.into_iter().zip(turns) { + queue[position].turn = turn; + } + true + } + pub fn requeue_front(&self, session_id: &str, turn: T, priority: DialogQueuePriority) { self.inner .entry(session_id.to_string()) @@ -1075,6 +1117,29 @@ mod tests { )); } + #[test] + fn dialog_turn_queue_reorder_preserves_unmanaged_slots_and_priority_lanes() { + let queue = DialogTurnQueue::with_max_depth(8); + for (id, priority) in [ + ("high", DialogQueuePriority::High), + ("a", DialogQueuePriority::Normal), + ("unmanaged", DialogQueuePriority::Normal), + ("b", DialogQueuePriority::Normal), + ] { + queue.enqueue("s", id.to_string(), priority).unwrap(); + } + assert!(!queue.reorder_subset("s", &["a".into(), "a".into()], |s| Some(s.as_str()))); + assert!(!queue.reorder_subset("s", &["a".into(), "high".into()], |s| Some(s.as_str()))); + assert!(!queue.reorder_subset("s", &["missing".into()], |s| Some(s.as_str()))); + assert!(queue.reorder_subset("s", &["b".into(), "a".into()], |s| Some(s.as_str()))); + assert_eq!( + (0..4) + .map(|_| queue.dequeue_next("s").unwrap()) + .collect::>(), + ["high", "b", "unmanaged", "a"] + ); + } + #[test] fn dialog_turn_queue_reclaims_empty_session_entries() { let queue = DialogTurnQueue::with_max_depth(4); diff --git a/src/mobile-web/README.md b/src/mobile-web/README.md index 31dad352bd..858a0f3be4 100644 --- a/src/mobile-web/README.md +++ b/src/mobile-web/README.md @@ -92,6 +92,11 @@ the phone, or leaving the session does not stop host-side dispatch. still render steering inline within the active turn. The turn-scoped SDK steering API used by CLI/Dispatch retains its inline contract; this handoff belongs to host queue promotion. +- **Reorder** uses the drag handle, Up/Down while the handle is focused, or + Move up/down in **More**. The host confirms the new execution order before + the list changes. A concurrent update cancels a drag and asks you to retry + against the refreshed list. Older queue hosts without `supportsReorder` + retain Send now and Remove, with a clear sorting-unavailable message. - **Remove from queue** only removes an unstarted message. It never stops the active turn. An operation that lost a race with dispatch is rejected. - A failed turn or unconsumed steering retains the message as blocked on the diff --git a/src/mobile-web/src/components/MobileHostQueue.tsx b/src/mobile-web/src/components/MobileHostQueue.tsx index 1a3853b35c..a16352c4bc 100644 --- a/src/mobile-web/src/components/MobileHostQueue.tsx +++ b/src/mobile-web/src/components/MobileHostQueue.tsx @@ -1,14 +1,16 @@ import React, { useEffect, useId, useState, useSyncExternalStore } from 'react'; -import { MobileButton, MobileBanner, MobileIconButton } from '@openbitfun/ui/mobile'; +import { MobileButton, MobileBanner, MobileIconButton, MobileSheet } from '@openbitfun/ui/mobile'; import { HostDialogQueue, observeHostQueue } from '../../../shared/dialog-queue/HostDialogQueue'; +import { useQueueReorder } from '@openbitfun/ui/flow-chat'; import { useI18n } from '../i18n'; -import { ArrowUp, ChevronDown, ChevronUp, Info, X } from 'lucide-react'; +import { ArrowUp, ArrowDown, CornerDownRight, GripVertical, MoreHorizontal, Paperclip, Trash2, ChevronDown, ChevronUp, Info } from 'lucide-react'; import '../styles/host-queue.scss'; export function MobileHostQueue({ queue, onRestore }: { queue: HostDialogQueue; onRestore: (text: string) => void }) { const { t } = useI18n(); const view = useSyncExternalStore(queue.subscribe, queue.getSnapshot, queue.getSnapshot); const [expanded, setExpanded] = useState(true); + const [selectedId, setSelectedId] = useState(null); const [showHelp, setShowHelp] = useState(false); const listId = useId(); const helpId = useId(); @@ -20,6 +22,15 @@ export function MobileHostQueue({ queue, onRestore }: { queue: HostDialogQueue; try { await action(); } catch (e) { setError(String(e)); } finally { setBusy(false); } }; + const items = view.snapshot?.items ?? []; + const reorderIds = items.filter(item => item.status === 'queued').map(item => item.turnId); + const reorderEnabled = !busy && !view.error && view.snapshot?.supportsReorder === true; + const reorder = useQueueReorder(reorderIds, reorderEnabled, `${view.snapshot?.queueEpoch}:${view.snapshot?.revision}`, + (id, before) => void run(() => queue.reorder(id, before))); + const selected = items.find(item => item.turnId === selectedId); + const selectedIndex = selected ? reorderIds.indexOf(selected.turnId) : -1; + const rawError = error || view.error; + const visibleError = rawError?.includes('queue_conflict:') ? t('queue.orderChanged') : rawError; const count = (view.snapshot?.items.length ?? 0) + view.pending.length; if (!view.snapshot?.items.length && !view.pending.length && !view.error && !error) return null; return
    @@ -34,23 +45,27 @@ export function MobileHostQueue({ queue, onRestore }: { queue: HostDialogQueue; icon={
    ; } diff --git a/src/mobile-web/src/i18n/messages.ts b/src/mobile-web/src/i18n/messages.ts index 91877c3905..2bf813447c 100644 --- a/src/mobile-web/src/i18n/messages.ts +++ b/src/mobile-web/src/i18n/messages.ts @@ -10,6 +10,12 @@ export const messages: Record = { 'en-US': { backgroundDelivery: { quiet: 'Background task completed · No report needed', running: 'Background task running' }, queue: { + "reorder": "Drag to reorder, or use Up and Down arrow keys", + "moveUp": "Move up", + "moveDown": "Move down", + "orderChanged": "The queue changed. Refresh it before reordering.", + "reorderUnsupported": "Update the execution host to reorder queued messages.", + "title": "Queued messages", "about": "About queued messages", "memoryNotice": "Accepted messages run while this page is closed. Restarting the execution device clears pending messages.", @@ -382,6 +388,12 @@ export const messages: Record = { 'zh-CN': { backgroundDelivery: { quiet: '后台任务已完成 · 无需汇报', running: '后台任务执行中' }, queue: { + "reorder": "拖动排序,也可使用上下方向键", + "moveUp": "上移", + "moveDown": "下移", + "orderChanged": "队列已变化,请刷新后重新调整顺序。", + "reorderUnsupported": "升级执行端后可调整排队消息的顺序。", + "title": "待发送", "about": "排队消息说明", "memoryNotice": "消息接受后,关闭此页面仍会执行。执行设备重启会清空待执行消息。", @@ -754,6 +766,12 @@ export const messages: Record = { 'zh-TW': { backgroundDelivery: { quiet: '背景任務已完成 · 無需回報', running: '背景任務執行中' }, queue: { + "reorder": "拖曳排序,也可使用上下方向鍵", + "moveUp": "上移", + "moveDown": "下移", + "orderChanged": "佇列已變更,請重新整理後再調整順序。", + "reorderUnsupported": "升級執行端後可調整排隊訊息的順序。", + "title": "待傳送", "about": "排隊訊息說明", "memoryNotice": "訊息接受後,關閉此頁面仍會執行。執行裝置重新啟動會清空待執行訊息。", diff --git a/src/mobile-web/src/styles/host-queue.scss b/src/mobile-web/src/styles/host-queue.scss index 75af2e622a..52676918ea 100644 --- a/src/mobile-web/src/styles/host-queue.scss +++ b/src/mobile-web/src/styles/host-queue.scss @@ -3,23 +3,22 @@ min-width: 0; overflow: hidden; flex-shrink: 0; - border: 1px solid var(--openbitfun-color-border-subtle); - border-radius: 20px; - background: var(--openbitfun-color-surface-panel); + border: 0; + background: transparent; color: var(--openbitfun-color-content-primary); font-size: var(--openbitfun-type-body-sm-font-size); line-height: var(--openbitfun-type-body-sm-line-height); - // 7px + half a 40px queue control matches the composer: 5px + half of 44px. - &__header { display: flex; align-items: center; padding: 0 7px 0 12px; } + // Match the composer control centerline with the same 44px target, 5px inset and 1px composer border. + &__header { display: flex; align-items: center; padding: 0 6px 0 12px; } &__toggle { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; - min-height: 40px; - height: 40px; + min-height: 44px; + height: 44px; padding: 0; border: 0; background: transparent; @@ -33,31 +32,45 @@ &:focus-visible { outline: 2px solid var(--openbitfun-color-focus-ring); outline-offset: -2px; border-radius: 8px; } } &__icon { - width: 40px; - height: 40px; - min-width: 40px; - min-height: 40px; + width: 44px; + height: 44px; + min-width: 44px; + min-height: 44px; padding: 0; flex-shrink: 0; color: var(--openbitfun-color-content-secondary); } - &__row { display: flex; align-items: center; gap: 4px; } + &__row { position: relative; display: flex; align-items: flex-start; gap: 4px; } + &__row::before, &__recovery::before { + content: ''; position: absolute; inset-inline: 8px; top: 0; + border-top: 1px solid var(--openbitfun-color-border-subtle); pointer-events: none; + } + &__recovery { position: relative; } + &__line { display: flex; align-items: center; min-height: 44px; gap: 6px; } + &__line &__preview { flex: 0 1 auto; margin: 0; } + &__attachments { display: inline-flex; align-items: center; gap: 3px; flex-shrink: 0; color: var(--openbitfun-color-content-secondary); } + &__handle { width: 44px; min-width: 44px; height: 44px; min-height: 44px; padding: 0; touch-action: none; cursor: grab; user-select: none; } + &__row[data-queue-dragging] { z-index: 1; background: var(--openbitfun-color-surface-panel); box-shadow: var(--openbitfun-shadow-sm); } + &__row[data-queue-drop="before"] { box-shadow: inset 0 2px var(--openbitfun-color-focus-ring); } + &__row[data-queue-drop="after"] { box-shadow: inset 0 -2px var(--openbitfun-color-focus-ring); } + &__full-preview { white-space: pre-wrap; overflow-wrap: anywhere; } + &__sheet-actions { display: flex; flex-wrap: wrap; gap: 8px; } &__message { flex: 1; min-width: 0; } &__row &__actions { flex-wrap: nowrap; gap: 0; margin: 0; } &__count, &__status, &__help { color: var(--openbitfun-color-content-secondary); } &__help { margin: 0; padding: 0 12px 12px; } - &__body { + &__list { max-height: min(240px, calc(var(--mobile-viewport-height) * 0.28)); overflow-y: auto; overscroll-behavior: contain; - } - &__list { list-style: none; margin: 0; - padding: 0 7px 0 12px; - li { padding: 4px 0; border-top: 1px solid var(--openbitfun-color-border-subtle); } + padding: 0 6px 0 12px; + li { padding: 4px 0; } p { margin: 0 0 4px; } } &__preview { white-space: pre-wrap; overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } &__actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin-top: 4px; } } + +.chat-page__input-wrap:has(> .host-message-queue) { gap: 0; } diff --git a/src/mobile-web/tests/fixtures/host-queue.tsx b/src/mobile-web/tests/fixtures/host-queue.tsx index fc92816828..23c6651a52 100644 --- a/src/mobile-web/tests/fixtures/host-queue.tsx +++ b/src/mobile-web/tests/fixtures/host-queue.tsx @@ -20,10 +20,18 @@ export function mountHostQueueFixture({ count = 1, expanded = true } = {}) { const calls: string[] = []; let items = Array.from({ length: count }, (_, index) => ({ turnId: `queued-${index}`, displayContent: index === 0 ? '接着检查错误处理和测试覆盖' : `排队消息 ${index + 1}:分析当前项目的实现,检查可能的问题。`, previewTruncated: false, attachmentCount: 0, agentType: 'Standard', createdAtMs: 1, status: 'queued' as const, reason: null, targetTurnId: null, steeringId: null })); + let revision = 1; const queue = new HostDialogQueue('ui-fixture', 'session', async request => { calls.push(request.action); + if (request.action === 'reorder') { + if (request.expectedRevision !== revision) throw new Error('queue_conflict: queue changed'); + const item = items.find(item => item.turnId === request.turnId)!; + items = items.filter(value => value !== item); + items.splice(request.beforeTurnId === null ? items.length : items.findIndex(value => value.turnId === request.beforeTurnId), 0, item); + } if (request.action === 'cancel' || request.action === 'promote') items = items.filter(item => item.turnId !== request.turnId); - return { sessionId: 'session', queueEpoch: 'epoch', revision: calls.length, activeTurnId: 'active', + if (request.action !== 'list' && request.action !== 'get') revision++; + return { sessionId: 'session', queueEpoch: 'epoch', supportsReorder: true, revision, activeTurnId: 'active', items, capacity: 20, used: items.length, receipt: null }; }); const noop = () => {}; @@ -48,5 +56,5 @@ export function mountHostQueueFixture({ count = 1, expanded = true } = {}) { ; } root.render(); - return { calls, dispose: () => root.unmount() }; + return { calls, queue, dispose: () => root.unmount() }; } diff --git a/src/mobile-web/tests/host-dialog-queue-browser.test.mjs b/src/mobile-web/tests/host-dialog-queue-browser.test.mjs index 64703aaddb..2567eb7b7a 100644 --- a/src/mobile-web/tests/host-dialog-queue-browser.test.mjs +++ b/src/mobile-web/tests/host-dialog-queue-browser.test.mjs @@ -86,7 +86,7 @@ test('queue stays above the measured composer across phone, keyboard-height and const layout=await page.evaluate(()=>{ const box=selector=>document.querySelector(selector).getBoundingClientRect(); const queue=box('.host-message-queue'),composer=box('.chat-page__composer'),wrap=box('.chat-page__input-wrap'); - const body=document.querySelector('.host-message-queue__body'); + const body=document.querySelector('.host-message-queue__list'); return {noOverlap:queue.bottom<=composer.top,inside:queue.top>=0&&composer.bottom<=innerHeight, width:document.body.scrollWidth<=innerWidth,aligned:Math.abs(queue.left-composer.left)<1&&Math.abs(queue.right-composer.right)<1, scrollable:body.scrollHeight>body.clientHeight,reserved:parseFloat(getComputedStyle(document.querySelector('.chat-page__messages')).paddingBottom)>=wrap.height}; @@ -100,8 +100,8 @@ test('queue stays above the measured composer across phone, keyboard-height and const r=stop.getBoundingClientRect(); return {info:center(info),cancel:center(cancel),stop:center(stop),width:r.width,height:r.height,radius:getComputedStyle(stop).borderRadius}; }); - assert.ok(Math.abs(controls.info-controls.cancel)<1, 'queue info and remove share a centerline'); - assert.ok(Math.abs(controls.cancel-controls.stop)<1, 'queue remove and stop share a centerline'); + assert.ok(Math.abs(controls.info-controls.cancel)<1, 'queue info and overflow share a centerline'); + assert.ok(Math.abs(controls.cancel-controls.stop)<1, 'queue overflow and stop share a centerline'); assert.equal(controls.width,controls.height); assert.equal(controls.radius,'50%', 'stop control is circular'); @@ -137,8 +137,59 @@ test('queue stays above the measured composer across phone, keyboard-height and assert.equal(await page.$('.host-message-queue__help'),null); await page.click('.host-message-queue__actions button'); await page.waitForFunction(()=>document.querySelectorAll('.host-message-queue li').length===1); - await page.click('[aria-label="移出队列"]'); + await page.click('.host-message-queue__actions button:last-child'); + await page.waitForFunction(() => { + const button = document.querySelector('.host-message-queue__sheet-actions button'); + if (!button) return false; + const rect = button.getBoundingClientRect(); + // Puppeteer's click does not wait for the sheet's entrance animation. + return rect.height > 0 && rect.top >= 0 && rect.bottom <= innerHeight; + }); + await page.click('.host-message-queue__sheet-actions button'); await page.waitForFunction(()=>!document.querySelector('.host-message-queue')); assert.ok(await page.$('.chat-page__composer'),'removing the last queued message preserves the composer'); }finally{await browser.close();await server.close();} }); + +test('touch-sized queue handles reorder real component rows and overflow removes the selected item', {timeout:60000}, async () => { + const server = await startSourceServer(); const browser = await launchBrowser(); + try { + const page = await browser.newPage(); await page.setViewport({width:320,height:568}); + await page.goto(server.origin + '/tests/fixtures/host-queue.html?count=3&theme=dark'); + await page.waitForSelector('.host-message-queue__handle'); + const geometry = await page.evaluate(() => { + const rows = document.querySelectorAll('.host-message-queue__row'); + const last = rows[rows.length - 1]; + const composer = document.querySelector('.chat-page__composer'); + return { + gap: composer.getBoundingClientRect().top - last.getBoundingClientRect().bottom, + firstLine: getComputedStyle(rows[0], '::before').borderTopWidth, + lastBottom: getComputedStyle(last, '::after').content, + outerBorder: getComputedStyle(document.querySelector('.host-message-queue')).borderTopWidth, + }; + }); + assert.deepEqual(geometry, {gap: 0, firstLine: '1px', lastBottom: 'none', outerBorder: '0px'}); + const handles = await page.$$('.host-message-queue__handle'); + assert.ok((await handles[0].boundingBox()).width >= 44); + const before = await page.$$eval('.host-message-queue__preview', nodes => nodes.map(n => n.textContent)); + await handles[2].focus(); await page.keyboard.press('ArrowUp'); + await page.waitForFunction(first => document.querySelectorAll('.host-message-queue__preview')[1].textContent === first, {}, before[2]); + assert.deepEqual(await page.$$eval('.host-message-queue__preview', nodes => nodes.map(n => n.textContent)), [before[0], before[2], before[1]]); + const first = await page.$('.host-message-queue__handle'); const box = await first.boundingBox(); + const last = await page.$eval('.host-message-queue__row:last-child', el => { const r=el.getBoundingClientRect();return {y:r.bottom-3}; }); + await page.mouse.move(box.x+box.width/2,box.y+box.height/2); await page.mouse.down(); + await page.mouse.move(box.x+box.width/2,last.y,{steps:6}); await page.mouse.up(); + await page.waitForFunction(first => document.querySelector('.host-message-queue__preview').textContent !== first, {}, before[0]); + await page.click('.host-message-queue__row .host-message-queue__actions button:last-child'); + await page.waitForFunction(() => { + const button = document.querySelector('.host-message-queue__sheet-actions button'); + if (!button) return false; + const rect = button.getBoundingClientRect(); + // Puppeteer's click does not wait for the sheet's entrance animation. + return rect.height > 0 && rect.top >= 0 && rect.bottom <= innerHeight; + }); + await page.click('.host-message-queue__sheet-actions button'); + await page.waitForFunction(() => document.querySelectorAll('.host-message-queue__row').length === 2); + assert.equal(await page.$eval('body', body=>body.scrollWidth<=innerWidth),true); + } finally { await browser.close(); await server.close(); } +}); diff --git a/src/mobile-web/tests/host-dialog-queue.test.mjs b/src/mobile-web/tests/host-dialog-queue.test.mjs index 626d663fd6..196c7dec0f 100644 --- a/src/mobile-web/tests/host-dialog-queue.test.mjs +++ b/src/mobile-web/tests/host-dialog-queue.test.mjs @@ -192,3 +192,48 @@ test('a page without Web Crypto randomUUID still queues a send and an operation' assert.match(f.calls.find(call=>call.action==='promote').operationId,uuid); assert.equal(f.executions,1); }); + +test('reorder is negotiated before any outbox or transport mutation', async () => { + const f = fixture(); const queue = f.create(); await queue.refresh(); + await assert.rejects(queue.reorder('a', 'b'), /queue_reorder_unsupported/); + assert.equal(f.calls.some(c => c.action === 'reorder'), false); + assert.equal(f.records.size, 0); +}); + +test('an ambiguous move retries the identical operation rather than applying another move', async () => { + const f = fixture(); let revision = 4; let ids = ['a', 'b']; let lose = true; const receipts = new Set(); const mutations = []; + const snapshot = () => ({ sessionId: 'session-a', queueEpoch: 'owner', revision, supportsReorder: true, + activeTurnId: 'active', items: ids.map(turnId => ({ turnId, status: 'queued', displayContent: turnId })), capacity: 20, used: 2, receipt: null }); + const queue = new HostDialogQueue('scope', 'session-a', async request => { + if (request.action === 'reorder') { + mutations.push(structuredClone(request)); + assert.ok([...f.records.values()].some(r => r.request.operationId === request.operationId)); + if (!receipts.has(request.operationId)) { + assert.equal(request.expectedRevision, revision); + receipts.add(request.operationId); ids = ['b', 'a']; revision++; + } + if (lose) { lose = false; throw new Error('Lost acknowledgement'); } + } + return snapshot(); + }, f.storage); + await queue.refresh(); + await assert.rejects(queue.reorder('b', 'a')); + assert.equal(queue.getSnapshot().pending.length, 1); + await queue.retry(queue.getSnapshot().pending[0]); + assert.deepEqual(mutations[1], mutations[0]); + assert.equal(revision, 5); + assert.deepEqual(queue.getSnapshot().snapshot.items.map(i => i.turnId), ['b', 'a']); + assert.equal(queue.getSnapshot().pending.length, 0); +}); + +test('a stale move is explicitly rejected and is not retained for replay', async () => { + const f = fixture(); const queue = new HostDialogQueue('scope', 'session-a', async request => { + if (request.action === 'reorder') throw new Error('queue_conflict: queue changed'); + return { sessionId: 'session-a', queueEpoch: 'owner', revision: 1, supportsReorder: true, + activeTurnId: null, items: [], capacity: 20, used: 0, receipt: null }; + }, f.storage); + await queue.refresh(); await assert.rejects(queue.reorder('b', 'a'), /queue_conflict/); + assert.equal(f.records.size, 0); + assert.equal(queue.getSnapshot().pending.length, 0); + assert.match(queue.getSnapshot().error, /queue_conflict/); +}); diff --git a/src/shared/dialog-queue/HostDialogQueue.ts b/src/shared/dialog-queue/HostDialogQueue.ts index 4d61179247..c4d234fb4b 100644 --- a/src/shared/dialog-queue/HostDialogQueue.ts +++ b/src/shared/dialog-queue/HostDialogQueue.ts @@ -19,10 +19,11 @@ export interface QueueItem { } export interface QueueSnapshot { sessionId: string; queueEpoch: string; revision: number; activeTurnId: string | null; - items: QueueItem[]; capacity: number; used: number; receipt: QueueItem | null; + items: QueueItem[]; supportsReorder?: boolean; capacity: number; used: number; receipt: QueueItem | null; } export type QueueAction = { action: 'list' } | { action: 'get'; turnId: string } | { action: 'submit'; message: QueueMessage } + | { action: 'reorder'; turnId: string; beforeTurnId: string | null; operationId: string; expectedRevision: number } | { action: 'cancel'; turnId: string; operationId: string } | { action: 'promote'; turnId: string; operationId: string; expectedActiveTurnId: string | null }; export type QueueRequest = QueueAction & { sessionId: string; queueEpoch?: string }; @@ -205,6 +206,19 @@ export class HostDialogQueue { return this.transmit({ scope: this.scope, key: JSON.stringify([this.scope, operationId]), request }); }); } + reorder(turnId: string, beforeTurnId: string | null, expected = this.view.snapshot): Promise { + return this.serialize(async () => { + if (!expected?.supportsReorder) throw new Error('queue_reorder_unsupported: update the execution host to reorder messages'); + if (this.view.error || expected.queueEpoch !== this.view.snapshot?.queueEpoch) { + throw new Error('queue_conflict: refresh the host queue before reordering'); + } + const operationId = newId(); + return this.transmit({ scope: this.scope, key: JSON.stringify([this.scope, operationId]), request: { + sessionId: this.sessionId, queueEpoch: expected.queueEpoch, action: 'reorder', + turnId, beforeTurnId, operationId, expectedRevision: expected.revision, + } }); + }); + } retry(record: QueueOutboxRecord): Promise { return this.serialize(async () => this.retryRecord(record, await this.refresh())); } diff --git a/src/web-ui/src/flow_chat/components/HostPendingQueuePanel.tsx b/src/web-ui/src/flow_chat/components/HostPendingQueuePanel.tsx index 741bdbdf24..640656e569 100644 --- a/src/web-ui/src/flow_chat/components/HostPendingQueuePanel.tsx +++ b/src/web-ui/src/flow_chat/components/HostPendingQueuePanel.tsx @@ -3,8 +3,9 @@ import type { QueuedMessage } from '../types/flow-chat'; import { useEffect, useId, useState, useSyncExternalStore, type ReactNode } from 'react'; import { useI18n } from '@/infrastructure/i18n'; import { Button, Icon, IconButton, OverflowText, Tooltip } from '@openbitfun/ui'; -import { ListEnd, Paperclip, RotateCw } from 'lucide-react'; +import { GripVertical, ListEnd, Paperclip, RotateCw } from 'lucide-react'; import './HostPendingQueuePanel.scss'; +import { useQueueReorder } from '@openbitfun/ui/flow-chat'; import { PendingQueueMessageActions } from './PendingQueueMessageActions'; import { usePendingQueueDisclosure } from './usePendingQueueDisclosure'; import { hostQueuePresentation, observePresentedHostQueue } from '../services/hostQueuePresentation'; @@ -62,7 +63,11 @@ export function HostPendingQueuePanel({ queue, onRestore }: { queue: HostDialogQ await queue.dismiss(saved); }; const items = (view.snapshot?.items ?? []).filter(item => item.status === 'blocked' || !projected.has(item.turnId)); - const visibleError = error || (view.error?.includes('Session is not loaded') ? null : view.error); + const reorderIds = items.filter(item => item.status === 'queued').map(item => item.turnId); + const reorder = useQueueReorder(reorderIds, !busy && !view.error && view.snapshot?.supportsReorder === true, + `${view.snapshot?.queueEpoch}:${view.snapshot?.revision}`, (id, before) => void run(() => queue.reorder(id, before))); + const rawError = error || (view.error?.includes('Session is not loaded') ? null : view.error); + const visibleError = rawError?.includes('queue_conflict:') ? t('pendingQueue.orderChanged') : rawError; if (!items.length && !view.pending.length && !visibleError) return null; const locked = busy || !!view.error; const renderPreview = (text: string) => { const steering = item.status === 'steering_pending'; const blocked = item.status === 'blocked'; - return } {...reorder.handleProps(item.turnId)} /> : undefined} leadingIcon={} state={blocked ? 'failed' : steering ? 'sending' : 'default'}> @@ -93,6 +100,10 @@ export function HostPendingQueuePanel({ queue, onRestore }: { queue: HostDialogQ })} removeLabel={t('hostQueue.cancel')} removeDisabled={locked || steering} onRemove={() => void run(() => queue.act(item, 'cancel'))} + onMoveUp={view.snapshot?.supportsReorder && item.status === 'queued' ? () => void run(() => queue.reorder(item.turnId, reorderIds[reorderIds.indexOf(item.turnId) - 1])) : undefined} + onMoveDown={view.snapshot?.supportsReorder && item.status === 'queued' ? () => void run(() => queue.reorder(item.turnId, reorderIds[reorderIds.indexOf(item.turnId) + 2] ?? null)) : undefined} + moveUpDisabled={locked || reorderIds.indexOf(item.turnId) <= 0} + moveDownDisabled={locked || reorderIds.indexOf(item.turnId) === reorderIds.length - 1} onCollapse={expanded ? toggle : undefined} onAbout={() => setShowHelp(value => !value)} /> ; @@ -141,7 +152,7 @@ export function HostPendingQueuePanel({ queue, onRestore }: { queue: HostDialogQ } onClick={() => setShowHelp(value => !value)} /> } - {showHelp &&

    {t('hostQueue.memoryNotice')}

    } + {showHelp &&

    {t('hostQueue.memoryNotice')}{!view.snapshot?.supportsReorder && ` ${t('pendingQueue.reorderUnsupported')}`}

    } {visibleError &&
    {visibleError} diff --git a/src/web-ui/src/flow_chat/components/PendingQueueMessageActions.tsx b/src/web-ui/src/flow_chat/components/PendingQueueMessageActions.tsx index 80be48a883..3edb26646d 100644 --- a/src/web-ui/src/flow_chat/components/PendingQueueMessageActions.tsx +++ b/src/web-ui/src/flow_chat/components/PendingQueueMessageActions.tsx @@ -16,6 +16,10 @@ interface PendingQueueMessageActionsProps { removeLabel: string; removeDisabled: boolean; onRemove: () => void; + onMoveUp?: () => void; + onMoveDown?: () => void; + moveUpDisabled?: boolean; + moveDownDisabled?: boolean; onCollapse?: () => void; onAbout?: () => void; } @@ -23,7 +27,7 @@ interface PendingQueueMessageActionsProps { export function PendingQueueMessageActions({ sendLabel, sendTooltip, sendAriaLabel, sendDisabled, sending, onSend, editLabel, editDisabled, onEdit, removeLabel, removeDisabled, onRemove, - onCollapse, onAbout, + onCollapse, onAbout, onMoveUp, onMoveDown, moveUpDisabled, moveDownDisabled, }: PendingQueueMessageActionsProps) { const { t } = useI18n('flow-chat'); const [open, setOpen] = useState(false); @@ -53,6 +57,8 @@ export function PendingQueueMessageActions({ setOpen(false)} placement="top" inlineSize="content" items={[ { id: 'edit', label: editLabel, icon: , disabled: editDisabled, onSelect: onEdit }, + ...(onMoveUp ? [{ id: 'move-up', label: t('pendingQueue.moveUp'), icon: , disabled: moveUpDisabled, onSelect: onMoveUp }] : []), + ...(onMoveDown ? [{ id: 'move-down', label: t('pendingQueue.moveDown'), icon: , disabled: moveDownDisabled, onSelect: onMoveDown }] : []), ...(onCollapse ? [{ id: 'collapse', label: t('pendingQueue.actions.collapse'), icon: , onSelect: onCollapse }] : []), ...(onAbout ? [{ id: 'about', label: t('hostQueue.about'), icon: , onSelect: onAbout }] : []), ]} /> diff --git a/src/web-ui/src/flow_chat/components/PendingQueuePanel.tsx b/src/web-ui/src/flow_chat/components/PendingQueuePanel.tsx index 90dd56972c..bad2ff624d 100644 --- a/src/web-ui/src/flow_chat/components/PendingQueuePanel.tsx +++ b/src/web-ui/src/flow_chat/components/PendingQueuePanel.tsx @@ -19,8 +19,8 @@ import { getActiveSurfaceScope, isSurfaceChangedError, onSurfaceActivated } from import { useCallback, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore } from 'react'; import { useTranslation } from 'react-i18next'; -import { ListEnd, Paperclip } from 'lucide-react'; -import { OverflowText } from '@openbitfun/ui'; +import { GripVertical, ListEnd, Paperclip } from 'lucide-react'; +import { IconButton, OverflowText } from '@openbitfun/ui'; import { stateMachineManager } from '../state-machine'; import { FlowChatStore } from '../store/FlowChatStore'; import { pendingQueueManager } from '../services/flow-chat-manager/PendingQueueModule'; @@ -33,6 +33,7 @@ import type { QueuedMessage, SteeringImage } from '../types/flow-chat'; import { isAcpFlowSession } from '../utils/acpSession'; import { getQueuedMessageAttachmentCount } from '../utils/pendingQueuePresentation'; import './PendingQueuePanel.scss'; +import { useQueueReorder } from '@openbitfun/ui/flow-chat'; import { PendingQueueMessageActions } from './PendingQueueMessageActions'; import { usePendingQueueDisclosure } from './usePendingQueueDisclosure'; import { Icon } from '@openbitfun/ui'; @@ -87,6 +88,12 @@ function LegacyPendingQueuePanel({ const [items, setItems] = useState(() => sessionId ? pendingQueueManager.list(sessionId) : [], ); + const reorderIds = items.map(item => item.id); + const reorderEnabled = !recoveryInFlight && !items.some(isSendingQueuedMessage); + const move = (id: string, before: string | null) => { + if (sessionId) pendingQueueManager.reorder(sessionId, id, before); + }; + const reorder = useQueueReorder(reorderIds, reorderEnabled, sessionId ?? '', move); const [isAcpSession, setIsAcpSession] = useState(() => { if (!sessionId) return false; return isAcpFlowSession(FlowChatStore.getInstance().getState().sessions.get(sessionId)); @@ -235,6 +242,9 @@ function LegacyPendingQueuePanel({ data-openbitfun-product-part="item" data-openbitfun-state={itemState === 'default' ? undefined : itemState} key={item.id} + {...reorder.rowProps(item.id)} + leadingControl={} {...reorder.handleProps(item.id)} />} state={itemState} leadingIcon={} > @@ -284,6 +294,10 @@ function LegacyPendingQueuePanel({ data-openbitfun-product-part="actions" > move(item.id, reorderIds[reorderIds.indexOf(item.id) - 1])} + onMoveDown={() => move(item.id, reorderIds[reorderIds.indexOf(item.id) + 2] ?? null)} + moveUpDisabled={!reorderEnabled || reorderIds.indexOf(item.id) <= 0} + moveDownDisabled={!reorderEnabled || reorderIds.indexOf(item.id) === reorderIds.length - 1} sendLabel={t('pendingQueue.actions.sendNowLabel')} sendAriaLabel={t('pendingQueue.actions.sendNow')} sendTooltip={t('pendingQueue.tooltip.sendNow')} diff --git a/src/web-ui/src/flow_chat/components/usePendingQueueDisclosure.ts b/src/web-ui/src/flow_chat/components/usePendingQueueDisclosure.ts index 67d4b79164..93e4515ba1 100644 --- a/src/web-ui/src/flow_chat/components/usePendingQueueDisclosure.ts +++ b/src/web-ui/src/flow_chat/components/usePendingQueueDisclosure.ts @@ -11,7 +11,9 @@ export function usePendingQueueDisclosure() { if (!restoreFocus.current) return; restoreFocus.current = false; if (expanded) { - listRef.current?.querySelector('[tabindex="0"], button:not(:disabled)')?.focus(); + const list = listRef.current; + (list?.querySelector('[data-openbitfun-product-part="preview"][tabindex="0"]') + ?? list?.querySelector('button:not(:disabled), [tabindex="0"]'))?.focus(); } else { toggleRef.current?.focus(); } diff --git a/src/web-ui/src/flow_chat/components/useQueueReorder.test.tsx b/src/web-ui/src/flow_chat/components/useQueueReorder.test.tsx new file mode 100644 index 0000000000..3a2c7d95d5 --- /dev/null +++ b/src/web-ui/src/flow_chat/components/useQueueReorder.test.tsx @@ -0,0 +1,75 @@ +/** @vitest-environment jsdom */ +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { useQueueReorder } from '@openbitfun/ui/flow-chat'; +let root: Root; +let container: HTMLDivElement; +const move = vi.fn(); +const captures = new WeakMap(); +function Fixture({ revision = 1, enabled = true, ids = ['a', 'b', 'c'] }) { + const reorder = useQueueReorder(ids, enabled, revision, move); + return
      {ids.map(id =>
    • )}
    ; +} +function render(revision = 1, enabled = true) { + act(() => root.render()); + container.querySelector('ul')!.getBoundingClientRect = () => ({ top: 0, bottom: 120, height: 120 }) as DOMRect; + container.querySelectorAll('li').forEach((row, i) => { + row.getBoundingClientRect = () => ({ top: i * 40, bottom: (i + 1) * 40, height: 40 }) as DOMRect; + }); +} +function pointer(type: string, y: number, target = container.querySelector('button')!, id = 1) { + const event = new MouseEvent(type, { bubbles: true, button: 0, clientY: y }); + Object.defineProperty(event, 'pointerId', { value: id }); + act(() => target.dispatchEvent(event)); +} +beforeEach(() => { + move.mockClear(); + vi.stubGlobal('requestAnimationFrame', vi.fn(() => 1)); + vi.stubGlobal('cancelAnimationFrame', vi.fn()); + HTMLElement.prototype.setPointerCapture = function(id) { captures.set(this, id); }; + HTMLElement.prototype.hasPointerCapture = function(id) { return captures.get(this) === id; }; + HTMLElement.prototype.releasePointerCapture = function() { captures.delete(this); }; + container = document.createElement('div'); document.body.append(container); root = createRoot(container); + render(); +}); +afterEach(() => { act(() => root.unmount()); container.remove(); vi.unstubAllGlobals(); }); +it('commits only once on release with the insertion target and ignores another pointer', () => { + pointer('pointerdown', 20); pointer('pointermove', 85); + expect(move).not.toHaveBeenCalled(); + expect(container.querySelector('li[data-queue-drop="before"]')?.textContent).toBe('c'); + pointer('pointerup', 85, container.querySelector('button')!, 2); + expect(move).not.toHaveBeenCalled(); + pointer('pointerup', 85); + expect(move).toHaveBeenCalledExactlyOnceWith('a', 'c'); + expect(container.querySelector('[data-queue-dragging]')).toBeNull(); +}); +it.each(['Escape', 'blur', 'pointercancel', 'lostpointercapture'])('cancels without a mutation on %s', event => { + pointer('pointerdown', 20); pointer('pointermove', 110); + if (event === 'Escape') act(() => window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))); + else if (event === 'blur') act(() => window.dispatchEvent(new Event('blur'))); + else pointer(event, 110); + pointer('pointerup', 110); + expect(move).not.toHaveBeenCalled(); +}); +it('host revision changes invalidate the entire gesture', () => { + pointer('pointerdown', 20); pointer('pointermove', 110); render(2); pointer('pointerup', 110); + expect(move).not.toHaveBeenCalled(); +}); +it('arrow keys expose reorder without dragging and unsupported hosts disable the handles', () => { + act(() => container.querySelector('button')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }))); + expect(move).toHaveBeenCalledExactlyOnceWith('a', 'c'); + move.mockClear(); render(1, false); + expect(container.querySelector('button')!.disabled).toBe(true); + pointer('pointerdown', 20); pointer('pointermove', 110); pointer('pointerup', 110); + expect(move).not.toHaveBeenCalled(); +}); + +it('restores keyboard focus after a host mutation disables and then re-enables the grip', () => { + const handle = container.querySelector('button')!; + act(() => { handle.focus(); handle.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true })); }); + render(1, false); + act(() => handle.blur()); + render(2, true); + expect(document.activeElement).toBe(handle); +}); diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.test.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.test.ts index 6be81d479f..2c303d5178 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.test.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.test.ts @@ -189,3 +189,16 @@ describe('PendingQueueModule', () => { )).toBe(true); }); }); + + +it('persists reordered payloads and refuses to move a queue during an active send', () => { + const sessionId = testSession(); + const first = pendingQueueManager.enqueue({ sessionId, content: 'first' }); + const second = pendingQueueManager.enqueue({ sessionId, content: 'second', turnId: 'stable-turn' }); + expect(pendingQueueManager.reorder(sessionId, second.id, first.id)).toBe(true); + const key = `openbitfun.flowChat.pendingQueue.v1.${encodeURIComponent(JSON.stringify([LOCAL_SURFACE_ID, sessionId]))}`; + expect(JSON.parse(window.localStorage.getItem(key)!).map((item: { content: string }) => item.content)).toEqual(['second', 'first']); + expect(JSON.parse(window.localStorage.getItem(key)!)[0].turnId).toBe('stable-turn'); + pendingQueueManager.setStatus(sessionId, second.id, 'sending'); + expect(pendingQueueManager.reorder(sessionId, first.id, second.id)).toBe(false); +}); diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.ts index 497a19a903..78033ee480 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.ts @@ -292,6 +292,21 @@ class PendingQueueManager { return true; } + /** Reorder saved work without changing payloads, retry state, or active sends. */ + reorder(sessionId: string, id: string, beforeId: string | null): boolean { + const items = this.queues.get(this.queueKey(sessionId)); + if (!items || items.some(item => item.status === 'sending' || item.status === 'sending_now')) return false; + const from = items.findIndex(item => item.id === id); + if (from < 0 || beforeId === id || (beforeId !== null && !items.some(item => item.id === beforeId))) return false; + const next = [...items]; + const [item] = next.splice(from, 1); + next.splice(beforeId === null ? next.length : next.findIndex(value => value.id === beforeId), 0, item); + this.queues.set(this.queueKey(sessionId), next); + this.persist(sessionId); + this.notify(sessionId); + return true; + } + /** Confirm a queued item for immediate idle-session drain without rebuilding its payload. */ promoteForExplicitDrain(sessionId: string, id: string): boolean { const items = this.queues.get(this.queueKey(sessionId)); diff --git a/src/web-ui/src/locales/en-US/flow-chat.json b/src/web-ui/src/locales/en-US/flow-chat.json index 2c38056647..e8d3862f02 100644 --- a/src/web-ui/src/locales/en-US/flow-chat.json +++ b/src/web-ui/src/locales/en-US/flow-chat.json @@ -3865,7 +3865,12 @@ "errors": { "composerNotEmpty": "Send or clear the current input and attachments before editing this queued message", "sendNowFailed": "Send now failed; please try again" - } + }, + "reorder": "Drag to reorder, or use Up and Down arrow keys", + "moveUp": "Move up", + "moveDown": "Move down", + "orderChanged": "The queue changed. Refresh it and try moving the message again.", + "reorderUnsupported": "Update the execution host to reorder queued messages." }, "steering": { "title": "Steer", diff --git a/src/web-ui/src/locales/zh-CN/flow-chat.json b/src/web-ui/src/locales/zh-CN/flow-chat.json index f079d404a8..9706b137ea 100644 --- a/src/web-ui/src/locales/zh-CN/flow-chat.json +++ b/src/web-ui/src/locales/zh-CN/flow-chat.json @@ -3865,7 +3865,12 @@ "errors": { "composerNotEmpty": "请先发送或清空当前输入和附件,再编辑这条等待发送的消息", "sendNowFailed": "立即发送失败,请稍后重试" - } + }, + "reorder": "拖动排序,也可使用上下方向键", + "moveUp": "上移", + "moveDown": "下移", + "orderChanged": "队列已变化,请刷新后重新调整顺序。", + "reorderUnsupported": "升级执行端后可调整排队消息的顺序。" }, "steering": { "title": "立即引导", diff --git a/src/web-ui/src/locales/zh-TW/flow-chat.json b/src/web-ui/src/locales/zh-TW/flow-chat.json index f6ddd1bb7b..bf3ada92b6 100644 --- a/src/web-ui/src/locales/zh-TW/flow-chat.json +++ b/src/web-ui/src/locales/zh-TW/flow-chat.json @@ -3865,7 +3865,12 @@ "errors": { "composerNotEmpty": "請先發送或清空目前輸入與附件,再編輯這則等待發送的訊息", "sendNowFailed": "立即發送失敗,請稍後重試" - } + }, + "reorder": "拖曳排序,也可使用上下方向鍵", + "moveUp": "上移", + "moveDown": "下移", + "orderChanged": "佇列已變更,請重新整理後再調整順序。", + "reorderUnsupported": "升級執行端後可調整排隊訊息的順序。" }, "steering": { "title": "立即引導",