Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

fix(portal): no dead ends in the composer and sidebar while Portal works (#8188)

Mike Bradleycc79dd38053a
diff --git a/ods/extensions/services/dashboard-api/routers/pixel.py b/ods/extensions/services/dashboard-api/routers/pixel.py
index 5fa14735b..7defe7ff8 100644
--- a/ods/extensions/services/dashboard-api/routers/pixel.py
+++ b/ods/extensions/services/dashboard-api/routers/pixel.py
@@ -1153,6 +1153,17 @@ async def _produce_retained_result(store, identity, body, config, messages, *, o
admission_rejected = json.loads(raw) == {"error": "pixel_transition_in_progress"}
except (ValueError, UnicodeDecodeError):
pass
+ elif upstream.status_code == 429:
+ # Edge has one image slot. It refuses another image turn
+ # with this exact body before admitting it, so nothing
+ # ran: tell the owner Portal was busy, not that it failed.
+ try:
+ raw = await _bounded_response_bytes(upstream, 1024)
+ if json.loads(raw) == {"error": "image processing busy; retry shortly"}:
+ admission_rejected = True
+ admission_code = "image_turn_busy"
+ except (ValueError, UnicodeDecodeError):
+ pass
if upstream.status_code != 200 or not upstream.headers.get("content-type", "").lower().startswith("text/event-stream"):
raise ValueError("Invalid upstream stream")
buffered = bytearray()
diff --git a/ods/extensions/services/dashboard-api/tests/test_pixel_chat_results.py b/ods/extensions/services/dashboard-api/tests/test_pixel_chat_results.py
index 438aaeee1..0974b115d 100644
--- a/ods/extensions/services/dashboard-api/tests/test_pixel_chat_results.py
+++ b/ods/extensions/services/dashboard-api/tests/test_pixel_chat_results.py
@@ -78,6 +78,31 @@ def test_admission_rejection_is_typed_terminal_and_replays_without_execution(sto
asyncio.run(run())
[email protected]("payload,expected", [
+ ({"error": "image processing busy; retry shortly"}, "rejected"),
+ ({"error": "image processing busy; retry shortly", "private": "secret"}, "interrupted"),
+ ({"error": "different_busy"}, "interrupted"),
+])
+def test_busy_image_slot_is_a_typed_refusal_that_never_ran(store, monkeypatch, payload, expected):
+ # Edge holds one image slot; a second picture gets its exact 429 before
+ # admission. Only that body may tell the owner "busy, send again".
+ async def run():
+ monkeypatch.setattr(pixel.httpx, "AsyncClient", lambda **kw: FakeClient(
+ FakeResponse(status=429, chunks=[json.dumps(payload).encode()])))
+ async def forbidden(*args):
+ raise AssertionError("A refused turn must not cancel or inspect an agent run")
+ monkeypatch.setattr(pixel, "_cancel_edge_run", forbidden)
+ monkeypatch.setattr(pixel, "pixel_chat_activity", forbidden)
+ response = await pixel.pixel_chat_stream(Request({"type": "http"}), body(), OWNER)
+ await asyncio.gather(*list(pixel._result_tasks.values()))
+ data = await stream_body(response)
+ assert store.get(IDENTITY)["state"] == expected
+ assert (b'"code": "image_turn_busy"' in data) == (expected == "rejected")
+ assert b"secret" not in data and b"retry shortly" not in data
+ assert not store.has_pending(IDENTITY[:2])
+ asyncio.run(run())
+
+
def test_upstream_sse_cannot_forge_an_unstarted_admission_receipt(store, monkeypatch):
async def run():
frames = b'data: {"error":{"type":"pixel_dashboard_error","code":"transition_in_progress"}}\n\ndata: [DONE]\n\n'
diff --git a/ods/extensions/services/dashboard/src/components/PixelCommandSearch.jsx b/ods/extensions/services/dashboard/src/components/PixelCommandSearch.jsx
index 3caabde6e..e13c6901f 100644
--- a/ods/extensions/services/dashboard/src/components/PixelCommandSearch.jsx
+++ b/ods/extensions/services/dashboard/src/components/PixelCommandSearch.jsx
@@ -3,6 +3,7 @@ import { useNavigate } from 'react-router-dom'
import { Search, X, MessageSquare, Plus, Settings, ListChecks, Globe2 } from 'lucide-react'
import { readConversations, conversationTitle, SELECT_EVENT, LIBRARY_EVENT } from '../lib/pixelConversations'
import { conversationExcerpt } from '../lib/pixelConversationSearch'
+import { useNewTaskBlocked } from '../lib/portalTaskState'
export const OPEN_PIXEL_SEARCH = 'ods:pixel-search'
export default function PixelCommandSearch({ onInsert, onNewTask }) {
@@ -13,6 +14,8 @@ export default function PixelCommandSearch({ onInsert, onNewTask }) {
const [query, setQuery] = useState('')
const [chats, setChats] = useState([])
const [index, setIndex] = useState(0)
+ // Choosing it while Portal works shows the same reason beside the composer.
+ const newTaskBlocked = useNewTaskBlocked()
useEffect(() => {
const open = () => {
if (dialog.current.open) return
@@ -39,7 +42,7 @@ export default function PixelCommandSearch({ onInsert, onNewTask }) {
}
}, [])
const entries = [
- { title: 'New task', detail: 'Start a fresh conversation', icon: Plus, run: onNewTask },
+ { title: 'New task', detail: newTaskBlocked || 'Start a fresh conversation', icon: Plus, run: onNewTask },
{ title: 'Portal settings', detail: 'Connections, access and sharing', icon: Settings, run: () => navigate('/pixel/settings') },
{ title: 'Plan deep work', detail: 'Draft milestones and completion checks', icon: ListChecks, run: () => onInsert('Build a durable plan for this goal, then show the milestones and exact completion criteria before work begins.') },
{ title: 'Research with evidence', detail: 'Draft a research request with citations', icon: Globe2, run: () => onInsert('Research this question using current sources, inline citations, and explicit evidence-versus-inference labels.') },
diff --git a/ods/extensions/services/dashboard/src/components/PixelConversationNavigation.jsx b/ods/extensions/services/dashboard/src/components/PixelConversationNavigation.jsx
index b355092de..56d686e81 100644
--- a/ods/extensions/services/dashboard/src/components/PixelConversationNavigation.jsx
+++ b/ods/extensions/services/dashboard/src/components/PixelConversationNavigation.jsx
@@ -4,6 +4,7 @@ import {groupProjectConversations} from '../lib/conversationProjects'
import {EXAMPLE_OPEN_EVENT, EXAMPLE_REFRESH_EVENT, exampleProjectRows, readExampleProjects} from '../lib/exampleProjects'
import { CHAT_KEY, LIBRARY_EVENT, SELECT_EVENT, DELETE_EVENT, readConversations, conversationTitle } from '../lib/pixelConversations'
import { conversationLabels } from '../lib/pixelConversationLabels'
+import { useNewTaskBlocked } from '../lib/portalTaskState'
import PixelConversationRow, {ConversationTitle} from './PixelConversationRow'
import { exportConversation } from '../lib/pixelConversationExport'
@@ -22,6 +23,8 @@ export default function PixelConversationNavigation({ collapsed }) {
const [exportError, setExportError] = useState('')
const [showArchived, setShowArchived] = useState(false)
const [examples, setExamples] = useState([])
+ // While Portal finishes a task, New task is disabled and says why.
+ const newTaskBlocked = useNewTaskBlocked()
const archiveToggle = useRef(null)
const dialog = useRef(null)
@@ -85,7 +88,9 @@ export default function PixelConversationNavigation({ collapsed }) {
window.addEventListener(EXAMPLE_REFRESH_EVENT, load)
return () => { controller?.abort(); window.removeEventListener('focus', load); window.removeEventListener(EXAMPLE_REFRESH_EVENT, load) }
}, [])
- if (collapsed) return <button ref={newTask} className="pixel-nav-item" aria-label="New task" title="New task" onClick={() => window.dispatchEvent(new Event('ods:pixel-new-task'))}><Plus size={16}/></button>
+ // aria-disabled, not disabled: a click or tap still reaches Portal, which
+ // shows the reason beside the composer instead of doing nothing.
+ if (collapsed) return <button ref={newTask} className="pixel-nav-item rail-new-task" aria-label="New task" title={newTaskBlocked || 'New task'} aria-disabled={newTaskBlocked ? 'true' : undefined} onClick={() => window.dispatchEvent(new Event('ods:pixel-new-task'))}><Plus size={16}/></button>
const labeled = chats.map(chat => ({chat, labels:conversationLabels(chat.chatId)}))
const visible = labeled.filter(item => item.labels.archived === showArchived)
const pinned = visible.filter(item => item.labels.pinned).map(item => item.chat)
@@ -122,7 +127,9 @@ export default function PixelConversationNavigation({ collapsed }) {
{deleteError && <p role="alert">{deleteError}</p>}
<footer><button autoFocus disabled={deleting} onClick={closeDelete}>Cancel</button><button disabled={deleting} onClick={confirmDelete}>{deleting?'Deleting…':'Delete chat'}</button></footer>
</dialog>
- <button ref={newTask} className="pixel-nav-item" onClick={() => window.dispatchEvent(new Event('ods:pixel-new-task'))}><Plus size={16}/><span>New task</span></button>
+ <button ref={newTask} className="pixel-nav-item rail-new-task" aria-disabled={newTaskBlocked ? 'true' : undefined} aria-describedby={newTaskBlocked ? 'pixel-new-task-reason' : undefined} onClick={() => window.dispatchEvent(new Event('ods:pixel-new-task'))}><Plus size={16}/><span>New task</span></button>
+ {/* Described, not announced: the header already announces that Portal is working. */}
+ {newTaskBlocked && <p id="pixel-new-task-reason" className="rail-new-task-reason">{newTaskBlocked}</p>}
<div className="pixel-original-sections">
{pinned.length > 0 && <details className="rail-section" open><summary>Pinned{chevron}</summary>{rows(pinned, '')}</details>}
{projects.length+shipped.length>0 && <details className="rail-section" open>
diff --git a/ods/extensions/services/dashboard/src/lib/pixelComposerText.js b/ods/extensions/services/dashboard/src/lib/pixelComposerText.js
index 152eac588..02b12b497 100644
--- a/ods/extensions/services/dashboard/src/lib/pixelComposerText.js
+++ b/ods/extensions/services/dashboard/src/lib/pixelComposerText.js
@@ -3,3 +3,10 @@ export function appendComposerText(input, text) {
const separator = input && !input.endsWith(' ') && !input.endsWith('\n') ? ' ' : ''
return `${input}${separator}${text}`
}
+
+// A message that did not start goes back to the composer. Text typed while
+// Portal worked stays too: the unsent message first, then the newer draft.
+export function restoreUnsentDraft(current, unsent) {
+ if (!unsent || current === unsent || current.startsWith(`${unsent}\n\n`)) return current
+ return current.trim() ? `${unsent}\n\n${current}` : unsent
+}
diff --git a/ods/extensions/services/dashboard/src/lib/portalResponseFailure.js b/ods/extensions/services/dashboard/src/lib/portalResponseFailure.js
index a45f430c2..3b31312df 100644
--- a/ods/extensions/services/dashboard/src/lib/portalResponseFailure.js
+++ b/ods/extensions/services/dashboard/src/lib/portalResponseFailure.js
@@ -4,13 +4,27 @@ export function isProviderRateLimit(error) {
return error?.type === 'pixel_ingress_error' && error?.code === 'provider_rate_limited'
}
+// Portal refused the turn before starting it because another picture holds
+// its one image slot. Nothing ran, so the owner can simply send it again.
+export function isBusyRefusal(error) {
+ return error?.type === 'pixel_dashboard_error' && error?.code === 'image_turn_busy'
+}
+
export function isAdmissionRejected(error) {
- return error?.type === 'pixel_dashboard_error' && ['transition_in_progress', 'gateway_connect_refused'].includes(error?.code)
+ return error?.type === 'pixel_dashboard_error' && ['transition_in_progress', 'gateway_connect_refused', 'image_turn_busy'].includes(error?.code)
}
const ADMISSION_REJECTION_MESSAGE = 'Portal is holding new messages. This message was not started. Your draft is preserved; check Portal status before sending it again.'
+// A busy refusal is not a failure: no cause to hunt for, nothing to repair.
+export function busyRefusalText(withImages) {
+ return withImages
+ ? 'Portal is still working on another picture, so it did not start this message. Your message and pictures are kept; send them again in a moment.'
+ : 'Portal is busy with another request, so it did not start this message. Your message is kept; send it again in a moment.'
+}
+
export function portalResponseFailure(error) {
+ if (isBusyRefusal(error)) return busyRefusalText(true)
if (isAdmissionRejected(error)) {
return error.code === 'gateway_connect_refused'
? 'Portal did not start this attempt because its gateway was unavailable. Your draft is preserved; send it again when Portal is ready.'
diff --git a/ods/extensions/services/dashboard/src/lib/portalTaskState.js b/ods/extensions/services/dashboard/src/lib/portalTaskState.js
new file mode 100644
index 000000000..2f3ba372a
--- /dev/null
+++ b/ods/extensions/services/dashboard/src/lib/portalTaskState.js
@@ -0,0 +1,50 @@
+import {useSyncExternalStore} from 'react'
+
+// Portal streams one live task into this page, so a new task waits for it.
+// The default local model serves one request at a time (LLAMA_PARALLEL=1),
+// the Pixel edge takes one image turn at a time, and a task left mid-stream
+// cannot be reattached live: its chat shows only the final result later.
+// Team and goal runs are tracked by the server and never block a new task.
+const NEW_TASK_RUNNING = 'Portal is finishing the current task; you can start a new one when it’s done, or stop it.'
+const NEW_TASK_STOPPING = 'Portal is stopping the current task; you can start a new one when it has stopped.'
+const NEW_TASK_WAIT = 'Portal is finishing a step in this chat; you can start a new task in a moment.'
+
+export function newTaskBlockedReason({running, stopping, checking, launching, compacting}) {
+ if (stopping) return NEW_TASK_STOPPING
+ if (running) return NEW_TASK_RUNNING
+ return checking || launching || compacting ? NEW_TASK_WAIT : ''
+}
+
+// The composer stays editable while Portal works. Sending waits, and says why
+// instead of doing nothing.
+export function sendBlockedReason({deleted, running, stopping, waiting, ready}) {
+ if (deleted) return ''
+ if (stopping) return 'Portal is stopping the current task. Your message is kept here; send it when Portal has stopped.'
+ if (running) return 'Portal is finishing the current task. Your message is kept here; send it when Portal is done, or stop the task.'
+ if (waiting || !ready) return 'Portal is not ready for a new message yet. Your message is kept here; send it when Portal is ready.'
+ return ''
+}
+
+export const ATTACH_BLOCKED = 'Pictures can be added when Portal is ready for your next message. Your draft is kept.'
+
+// The sidebar and the command search live outside the Portal page. The page
+// publishes why a new task cannot start, so they can show it.
+let newTaskBlocked = ''
+const listeners = new Set()
+
+export function publishNewTaskBlocked(reason) {
+ const next = typeof reason === 'string' ? reason : ''
+ if (next === newTaskBlocked) return
+ newTaskBlocked = next
+ listeners.forEach(listener => listener())
+}
+
+function subscribe(listener) {
+ listeners.add(listener)
+ return () => listeners.delete(listener)
+}
+const snapshot = () => newTaskBlocked
+
+export function useNewTaskBlocked() {
+ return useSyncExternalStore(subscribe, snapshot, snapshot)
+}
diff --git a/ods/extensions/services/dashboard/src/pages/Pixel.jsx b/ods/extensions/services/dashboard/src/pages/Pixel.jsx
index a72569aea..bc6023c26 100644
--- a/ods/extensions/services/dashboard/src/pages/Pixel.jsx
+++ b/ods/extensions/services/dashboard/src/pages/Pixel.jsx
@@ -25,7 +25,8 @@ import PixelDraftPreview from '../components/PixelDraftPreview'
import PixelDictation from '../components/PixelDictation'
import PixelCommandSearch, { OPEN_PIXEL_SEARCH } from '../components/PixelCommandSearch'
import PixelConversationImport from '../components/PixelConversationImport'
-import { appendComposerText } from '../lib/pixelComposerText'
+import { appendComposerText, restoreUnsentDraft } from '../lib/pixelComposerText'
+import { ATTACH_BLOCKED, newTaskBlockedReason, publishNewTaskBlocked, sendBlockedReason } from '../lib/portalTaskState'
import PixelSelectionActions from '../components/PixelSelectionActions'
import PixelQuestions from '../components/PixelQuestions'
import PortalGoalPlan from '../components/PortalGoalPlan'
@@ -47,7 +48,7 @@ import { conversationProject } from '../lib/conversationProjects'
import PortalStreamingText from '../components/PortalStreamingText'
import PortalResponseActions from '../components/PortalResponseActions'
import PortalResponseError from '../components/PortalResponseError'
-import {isProviderRateLimit, isAdmissionRejected, portalResponseFailure} from '../lib/portalResponseFailure'
+import {isProviderRateLimit, isAdmissionRejected, isBusyRefusal, busyRefusalText, portalResponseFailure} from '../lib/portalResponseFailure'
import {publicationDisplayText} from '../lib/publicationDisplay'
import {isQuestionAnswer, parseQuestionsFrame, questionMetadata} from '../lib/pixelQuestions'
import PixelTurnNavigation from '../components/PixelTurnNavigation'
@@ -636,6 +637,9 @@ export default function Pixel({ systemStatus = null }) {
const [conversationDeleted, setConversationDeleted] = useState(() => initialChat?.conversationDeleted || false)
const [stopping, setStopping] = useState(false)
const [stopError, setStopError] = useState('')
+ // A turn Portal refused because it was busy; its draft is back in the composer.
+ const [refusal, setRefusal] = useState('')
+ const [sendHint, setSendHint] = useState(false)
const [exampleError, setExampleError] = useState(null)
const [restoredActivity, setRestoredActivity] = useState(() => initialChat?.interrupted ? 'checking' : 'idle')
const [activityRefresh, setActivityRefresh] = useState(0)
@@ -1117,10 +1121,12 @@ export default function Pixel({ systemStatus = null }) {
const context=teamAttempt.current.context
setMessages(previous=>previous.some(m=>m.teamRequestId===requestId) ? previous : [...previous,{role:'user',content:trimmed},{role:'assistant',content:requestedGoal?'Preparing your goal…':'Preparing the agent team…',teamRequestId:requestId,...(requestedGoal?{goalMode:true}:{}),status:'done'}])
setStopError('')
+ setRefusal('')
setExampleError(null)
try {
const team=await teams.start({request_id:requestId,task:teamCommand.task,context,...(requestedGoal?{mode:'goal'}:{})})
- if(team){setInput('');teamAttempt.current=null}
+ // The composer stays editable while the team launches; keep newer text.
+ if(team){setInput(value=>value===exactDraft?'':value);teamAttempt.current=null}
} catch(e){setStopError(e.message)}
return
}
@@ -1145,7 +1151,11 @@ export default function Pixel({ systemStatus = null }) {
updateRestoredActivity('idle')
setStopping(false)
setStopError('')
+ setRefusal('')
setExampleError(null)
+ // Text typed while this turn runs is a new draft. A turn that does not
+ // start returns its own text to the composer without replacing that draft.
+ const restoreDraft = () => setInput(current => restoreUnsentDraft(current, trimmed))
const controller = new AbortController()
abortRef.current = controller
@@ -1165,6 +1175,7 @@ export default function Pixel({ systemStatus = null }) {
let receivedDone = false
let receivedError = false
let admissionRejected = false
+ let busyRefused = false
let recoveryEligible = false
let verifiedPreview = null
let verifiedArtifacts = null
@@ -1237,6 +1248,12 @@ export default function Pixel({ systemStatus = null }) {
requestIdRef.current = null
throw new Error('chat-request-rejected')
}
+ if (response.status === 429) {
+ // Portal was busy (for example preparing another picture) and
+ // refused this turn before starting it. Nothing ran.
+ requestIdRef.current = null
+ return { kind: 'busy' }
+ }
if (!response.ok) throw new Error('chat unavailable')
reader = response.body?.getReader()
@@ -1271,6 +1288,7 @@ export default function Pixel({ systemStatus = null }) {
if (receivedError) continue
if (frame?.error) {
receivedError = true
+ busyRefused = !assistantText && isBusyRefusal(frame.error)
admissionRejected = !assistantText && isAdmissionRejected(frame.error)
const failureMessage = portalResponseFailure(frame.error)
setMessages(previous => replaceLastAssistant(previous, {
@@ -1313,6 +1331,11 @@ export default function Pixel({ systemStatus = null }) {
}
}
+ if (busyRefused && receivedDone) {
+ requestIdRef.current = null
+ setInterrupted(false)
+ return {kind:'busy'}
+ }
if (admissionRejected && receivedDone) {
requestIdRef.current = null
setInterrupted(false)
@@ -1370,7 +1393,7 @@ export default function Pixel({ systemStatus = null }) {
let attempt = await streamAttempt(chatIdRef.current, conversation, fullHistory)
if (!isCurrentTurn()) return
if (attempt.kind === 'deleted') {
- setInput(current => current || exactDraft)
+ setInput(current => restoreUnsentDraft(current, exactDraft))
contextStartRef.current = originalContextStart
setMessages(messages)
setConversationDeleted(true)
@@ -1378,15 +1401,24 @@ export default function Pixel({ systemStatus = null }) {
updateRestoredActivity('idle')
return
}
+ if (attempt.kind === 'busy') {
+ // Not a failure: the turn never started. It goes back to the
+ // composer with its pictures, and one click sends it again.
+ restoreDraft()
+ contextStartRef.current = originalContextStart
+ setMessages(messages)
+ setRefusal(busyRefusalText(turnImages.length > 0))
+ return
+ }
if (attempt.kind === 'rejected') {
- setInput(current => current || trimmed)
+ restoreDraft()
contextStartRef.current = originalContextStart
return
}
if (attempt.kind === 'switching') {
setStatus('switching')
setStatusDetail(attempt.detail)
- setInput(trimmed)
+ restoreDraft()
contextStartRef.current = originalContextStart
setMessages(messages)
return
@@ -1394,7 +1426,7 @@ export default function Pixel({ systemStatus = null }) {
if (attempt.kind === 'adaptive') {
setStatus('available')
setModelSupport(keepModelAdvisory)
- setInput(trimmed)
+ restoreDraft()
contextStartRef.current = originalContextStart
setMessages(messages)
return
@@ -1402,7 +1434,7 @@ export default function Pixel({ systemStatus = null }) {
if (!attempt.receivedError && attempt.receivedDone && attempt.recoveryEligible) {
if(needsImageRoute) {
- setInput(trimmed)
+ restoreDraft()
setMessages(previous=>replaceLastAssistant(previous,{content:'Portal could not recover this image conversation automatically. Your draft and images are preserved. Retry here after checking the conversation status.',status:'error'}))
return
}
@@ -1425,7 +1457,7 @@ export default function Pixel({ systemStatus = null }) {
attempt = await streamAttempt(retryChatId, [userMessage], fullHistory)
if (!isCurrentTurn()) return
if (attempt.kind === 'deleted') {
- setInput(current => current || exactDraft)
+ setInput(current => restoreUnsentDraft(current, exactDraft))
contextStartRef.current = originalContextStart
setMessages(messages)
setConversationDeleted(true)
@@ -1433,15 +1465,22 @@ export default function Pixel({ systemStatus = null }) {
updateRestoredActivity('idle')
return
}
+ if (attempt.kind === 'busy') {
+ contextStartRef.current = originalContextStart
+ setMessages(messages)
+ restoreDraft()
+ setRefusal(busyRefusalText(false))
+ return
+ }
if (attempt.kind === 'rejected') {
- setInput(current => current || trimmed)
+ restoreDraft()
contextStartRef.current = originalContextStart
return
}
if (attempt.kind === 'switching') {
contextStartRef.current = originalContextStart
setMessages(messages)
- setInput(trimmed)
+ restoreDraft()
setStatus('switching')
setStatusDetail(`${attempt.detail}. The clean-context request is preserved.`)
return
@@ -1449,7 +1488,7 @@ export default function Pixel({ systemStatus = null }) {
if (attempt.kind === 'adaptive') {
contextStartRef.current = originalContextStart
setMessages(messages)
- setInput(trimmed)
+ restoreDraft()
setStatus('available')
setModelSupport(keepModelAdvisory)
return
@@ -1467,7 +1506,7 @@ export default function Pixel({ systemStatus = null }) {
if(turnImages.length) {
if(attempt.receivedDone && !attempt.receivedError)images.clear()
- else setInput(trimmed)
+ else restoreDraft()
}
finishAttempt(attempt)
} catch (error) {
@@ -1477,7 +1516,7 @@ export default function Pixel({ systemStatus = null }) {
const historyTooLarge=error?.message==='history-request-too-large'
const requestRejected=error?.message==='chat-request-rejected'
setInterrupted(!storageFailed && !historyTooLarge && !requestRejected)
- if (storageFailed || historyTooLarge || requestRejected || turnImages.length) setInput(trimmed)
+ if (storageFailed || historyTooLarge || requestRejected || turnImages.length) restoreDraft()
setMessages(previous => replaceLastAssistant(previous, {
content: requestRejected?'Portal rejected the request format (HTTP 422). No task was started. Your draft is preserved. Refresh Portal before retrying.':historyTooLarge?'The encoded conversation exceeds the 8 MB request limit. No task was started. Export this conversation before starting a new chat.':conversationChanged ? 'This conversation changed in another tab. No task was started. Download a recovery copy, then reload to read the saved version.' : storageFailed ? 'Could not save the request for recovery. No task was started. Check browser storage and try again.' : latestAssistantText || 'Request failed',
status: 'error',
@@ -1576,8 +1615,17 @@ export default function Pixel({ systemStatus = null }) {
}
}, [stopping, interrupted, updateRestoredActivity])
+ // One live task streams into this page; see portalTaskState for why a new
+ // task waits for it. Every New task control shows this reason, never nothing.
+ const newTaskBlocked = newTaskBlockedReason({running:sending || restoredActive, stopping, checking:restoredChecking,
+ launching:teams.launching, compacting:contextControl.busy})
+ useEffect(() => { publishNewTaskBlocked(newTaskBlocked) }, [newTaskBlocked])
+ useEffect(() => () => publishNewTaskBlocked(''), [])
+
const startNewChat = useCallback((preserveDraft = false) => {
- if (sending || restoredActive || restoredChecking || stopping || teams.launching || contextControl.busy) return
+ if (newTaskBlocked) { setStopError(newTaskBlocked); return }
+ setRefusal('')
+ setSendHint(false)
chatIdRef.current = makeChatId()
images.replace(chatIdRef.current)
requestIdRef.current = null
@@ -1594,7 +1642,7 @@ export default function Pixel({ systemStatus = null }) {
setExampleError(null)
updateRestoredActivity('idle')
inputRef.current?.focus?.()
- }, [sending, restoredActive, restoredChecking, stopping, updateRestoredActivity, teams.launching,contextControl.busy,images.replace,input])
+ }, [newTaskBlocked, updateRestoredActivity, images.replace, input])
useEffect(() => {
const remove = async event => {
@@ -1621,8 +1669,9 @@ export default function Pixel({ systemStatus = null }) {
return () => window.removeEventListener(DELETE_EVENT, remove)
}, [sending, restoredActive, restoredChecking, stopping, startNewChat, teams.busy,contextControl.busy])
+ // Inserting only edits the draft, which stays editable while Portal works.
const insertComposerText = useCallback((text, { replace = false } = {}) => {
- if (sending || restoredActive || restoredChecking || stopping || contextControl.busy) return
+ if (conversationDeleted) return
setInput(value => {
if (replace) return text
const mode=agentCommand(text)?'agents':goalCommand(text)?'goal':null
@@ -1630,7 +1679,7 @@ export default function Pixel({ systemStatus = null }) {
return mode ? `/${mode} ${task}` : appendComposerText(value, text)
})
inputRef.current?.focus?.()
- }, [sending, restoredActive, restoredChecking, stopping,contextControl.busy])
+ }, [conversationDeleted])
useEffect(() => {
window.addEventListener('ods:pixel-new-task', startNewChat)
@@ -1714,6 +1763,8 @@ export default function Pixel({ systemStatus = null }) {
setPreviewRefresh(0)
setInput(chat.draft)
setStopError('')
+ setRefusal('')
+ setSendHint(false)
setExampleError(null)
setInterrupted(chat.interrupted)
setConversationDeleted(chat.conversationDeleted)
@@ -1729,6 +1780,12 @@ export default function Pixel({ systemStatus = null }) {
const inputOver = input.length > MAX_INPUT_LEN
const inputEmpty = !(command?.task ?? goalDraft?.task ?? input).trim() && !images.items.length
const isDisabled = conversationDeleted || sending || modelSwitching || restoredActive || restoredChecking || stopping || teams.busy || contextControl.busy || contextControl.historyUnknown || status !== 'available'
+ // Typing never waits for Portal: while it works on this chat the draft stays
+ // editable and is saved with the chat. Only sending waits, and says why.
+ const composerLocked = conversationDeleted || modelSwitching || status !== 'available'
+ const sendBlocked = sendBlockedReason({deleted:conversationDeleted, stopping, running:sending || restoredActive || teams.busy,
+ waiting:restoredChecking || contextControl.busy || contextControl.historyUnknown || modelSwitching, ready:status === 'available'})
+ useEffect(() => { if (!sendBlocked) setSendHint(false) }, [sendBlocked])
const composerVisible = !(workspaceExpanded && workspaceOpen && !previewCollapsed)
const typeIntoComposer = useCallback((character, start, end) => setInput(value => {
const agent = agentCommand(value)
@@ -1739,11 +1796,27 @@ export default function Pixel({ systemStatus = null }) {
const next = text.slice(0, from) + character + text.slice(to)
return agent ? `/agents ${next}` : goal ? `/goal ${next}` : next
}), [])
- const prepareComposerSend = useComposerFocus({ inputRef, disabled: isDisabled, visible: composerVisible, onType: typeIntoComposer })
+ const prepareComposerSend = useComposerFocus({ inputRef, disabled: composerLocked, visible: composerVisible, onType: typeIntoComposer })
const sendFromComposer = () => {
prepareComposerSend()
+ if (sendBlocked) {
+ // Enter while Portal works is never a silent no-op: the draft stays.
+ if (!inputEmpty) setSendHint(true)
+ return
+ }
void sendMessage()
}
+ // Pictures cannot join a turn while one is in flight (its own pictures are
+ // still attached). A drop or paste then says so instead of doing nothing,
+ // and a dropped file never replaces the page.
+ const hasFiles = transfer => Array.from(transfer?.types || []).includes('Files')
+ const dropFiles = event => {
+ const files = Array.from(event.dataTransfer?.files || [])
+ if (!files.length) return
+ event.preventDefault()
+ if (isDisabled) { setStopError(ATTACH_BLOCKED); return }
+ images.choose(files)
+ }
const integrationCommand = [...messages].reverse().find(message => message.role === 'user')?.content
const {recovery: integrationRecovery, resume: resumeProjectIntegration} = useExtensionProjectIntegration({
chatId: chatIdRef.current,
@@ -1804,7 +1877,7 @@ export default function Pixel({ systemStatus = null }) {
return (
<div className="pixel-chat flex flex-col overflow-hidden text-theme-text">
<div className={`pixel-chat-preview-layout flex min-h-0 flex-1 flex-col lg:flex-row ${!composerVisible ? 'is-workspace-expanded' : ''}`}>
- <div className="pixel-chat-column flex min-h-0 min-w-0 flex-1 flex-col">
+ <div className="pixel-chat-column flex min-h-0 min-w-0 flex-1 flex-col" onDragOver={event=>{if(hasFiles(event.dataTransfer))event.preventDefault()}} onDrop={dropFiles}>
{persistenceError && <PixelConversationRecovery error={persistenceError} chatId={chatIdRef.current} messages={messages} draft={input}/>}
<header className="pixel-chat-header">
<div className="pixel-chat-identity">
@@ -1851,9 +1924,9 @@ export default function Pixel({ systemStatus = null }) {
<button
type="button"
onClick={startNewChat}
- disabled={sending || restoredActive || restoredChecking || stopping || contextControl.busy}
- className="inline-flex items-center gap-1.5 rounded-none border-0 bg-transparent px-2.5 py-1.5 text-xs font-medium text-theme-text-secondary transition hover:text-theme-text disabled:cursor-not-allowed disabled:opacity-50"
- title="Start a new chat"
+ aria-disabled={newTaskBlocked ? 'true' : undefined}
+ className="inline-flex items-center gap-1.5 rounded-none border-0 bg-transparent px-2.5 py-1.5 text-xs font-medium text-theme-text-secondary transition hover:text-theme-text aria-disabled:cursor-not-allowed aria-disabled:opacity-50"
+ title={newTaskBlocked || 'Start a new chat'}
>
<Plus className="h-3.5 w-3.5" />
<span className="hidden sm:inline">New chat</span>
@@ -2029,11 +2102,7 @@ export default function Pixel({ systemStatus = null }) {
<div className="pixel-composer px-4 py-3 sm:px-6">
{chatScroll.showLatest && <div className="mb-2 text-center"><button type="button" onClick={chatScroll.jumpToLatest} className="portal-jump-latest">Jump to latest</button></div>}
- <div className={`portal-glass-composer mx-auto max-w-5xl ${messages.length===0 ? 'portal-neon-prompt' : ''}`} onDragOver={event=>{if(!isDisabled && Array.from(event.dataTransfer?.types || []).includes('Files'))event.preventDefault()}} onDrop={event=>{
- if(isDisabled)return
- const files=Array.from(event.dataTransfer?.files || [])
- if(files.length){event.preventDefault();images.choose(files)}
- }}>
+ <div className={`portal-glass-composer mx-auto max-w-5xl ${messages.length===0 ? 'portal-neon-prompt' : ''}`}>
<PortalImageAttachments attachments={images} chatId={chatIdRef.current} disabled={isDisabled} hasHistory={hasImageHistory} model={imageModel} onRefresh={()=>void contextControl.refresh(true)}/>
{command && <div className="mb-2 flex flex-wrap items-center gap-2 rounded-xl bg-theme-card/70 px-3 py-2 text-xs text-theme-text-secondary" role="group" aria-label="Agent team mode"><span className="font-medium text-theme-text">Agent team</span><span>Describe your task. Portal will choose the team.</span><button type="button" disabled={isDisabled} onClick={()=>setInput(command.task)} className="ml-auto whitespace-nowrap rounded px-2 py-1 hover:bg-theme-border/30">Exit team mode</button></div>}
{goalDraft && <div className="portal-goal-mode" role="group" aria-label="Goal mode"><span>Goal</span><small>Describe the outcome. Portal will plan, work and check its progress.</small><button type="button" disabled={isDisabled} onClick={()=>setInput(goalDraft.task)}>Exit goal mode</button></div>}
@@ -2043,7 +2112,13 @@ export default function Pixel({ systemStatus = null }) {
ref={inputRef}
value={command ? command.task : goalDraft ? goalDraft.task : input}
onChange={(event) => setInput(command ? `/agents ${event.target.value}` : goalDraft ? `/goal ${event.target.value}` : event.target.value)}
- onPaste={event=>{const files=Array.from(event.clipboardData?.items || []).filter(item=>item.kind==='file').map(item=>item.getAsFile()).filter(Boolean);if(files.length && !isDisabled){event.preventDefault();images.choose(files)}}}
+ onPaste={event=>{
+ const files=Array.from(event.clipboardData?.items || []).filter(item=>item.kind==='file').map(item=>item.getAsFile()).filter(Boolean)
+ if(!files.length)return
+ // Pasted text still lands; only the picture waits, and says so.
+ if(isDisabled){setStopError(ATTACH_BLOCKED);return}
+ event.preventDefault();images.choose(files)
+ }}
onKeyDown={(event) => {
if (shouldSendMessage(event, sendKey.mode)) {
event.preventDefault()
@@ -2061,7 +2136,7 @@ export default function Pixel({ systemStatus = null }) {
: status === 'recovery'
? 'Messages are held until Portal recovery'
: `${displayName} is unavailable`}
- disabled={isDisabled}
+ disabled={composerLocked}
rows={1}
className={`pixel-composer-input min-h-11 flex-1 resize-none rounded-xl border bg-theme-card px-4 py-2.5 text-sm text-theme-text outline-none transition placeholder:text-theme-text-muted/70 disabled:opacity-50 ${
inputOver ? 'border-red-400' : 'border-theme-border'
@@ -2091,6 +2166,11 @@ export default function Pixel({ systemStatus = null }) {
</div>
</div>
{stopError && <p role="alert" className="mt-1.5 px-1 text-xs text-theme-text-secondary">{stopError}</p>}
+ {sendHint && sendBlocked && <p role="status" className="mt-1.5 px-1 text-xs text-theme-text-secondary">{sendBlocked}</p>}
+ {refusal && !inputEmpty && <div className="portal-context-status" role="status" aria-label="Message not started">
+ <span>{refusal}</span>
+ <button type="button" onClick={sendFromComposer}>Send again</button>
+ </div>}
{exampleError && <p role="alert" className="mt-1.5 px-1 text-xs text-theme-text-secondary">{exampleError.text}{exampleError.help && <> <HelpLink /></>}</p>}
{contextControl.historyUnknown && <div className="portal-context-status" role="status">
{contextControl.resolving && <Loader2 size={13} className="animate-spin" aria-hidden="true"/>}
diff --git a/ods/extensions/services/dashboard/src/pages/Pixel.legacy-history.test.jsx b/ods/extensions/services/dashboard/src/pages/Pixel.legacy-history.test.jsx
index d69f88fa9..06e21fb92 100644
--- a/ods/extensions/services/dashboard/src/pages/Pixel.legacy-history.test.jsx
+++ b/ods/extensions/services/dashboard/src/pages/Pixel.legacy-history.test.jsx
@@ -62,7 +62,9 @@ test('restores the library-first request receipt before checking interrupted wor
await screen.findByText('Working in this chat')
expect(screen.getByRole('textbox')).toBeDisabled()
resolveHealth({ok: true, json: async () => ({available: true})})
- expect(await screen.findByPlaceholderText(/^Message .+\.\.\.$/)).toBeDisabled()
+ // The draft is editable while the earlier work runs; sending waits for it.
+ expect(await screen.findByPlaceholderText(/^Message .+\.\.\.$/)).toBeEnabled()
+ expect(screen.queryByTitle('Send')).toBeNull()
// Moving the legacy authority into the current pointer must keep its live
// flags intact; interrupted is the observer's view, not a persisted edit.
expect(JSON.parse(localStorage.getItem(CHAT_KEY))).toMatchObject({requestId: 'latest-request', inFlight: true, interrupted: false})
diff --git a/ods/extensions/services/dashboard/src/pages/Pixel.test.jsx b/ods/extensions/services/dashboard/src/pages/Pixel.test.jsx
index 62e09f627..f3b1c302c 100644
--- a/ods/extensions/services/dashboard/src/pages/Pixel.test.jsx
+++ b/ods/extensions/services/dashboard/src/pages/Pixel.test.jsx
@@ -2138,8 +2138,11 @@ describe('Pixel', () => {
render(<Pixel />)
await screen.findByText('Working in this chat')
expect(screen.getByTitle('Stop')).toBeEnabled()
- expect(screen.getByPlaceholderText('Message Portal...')).toBeDisabled()
- expect(screen.getByTitle('Start a new chat')).toBeDisabled()
+ // The draft stays editable; only sending and New chat wait, with a reason.
+ expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
+ expect(screen.queryByTitle('Send')).toBeNull()
+ expect(screen.getByRole('button', {name:'New chat'})).toHaveAttribute('aria-disabled', 'true')
+ expect(screen.getByRole('button', {name:'New chat'})).toHaveAttribute('title', expect.stringContaining('Portal is finishing the current task'))
expect(screen.getByText('Saved partial result')).toBeInTheDocument()
state = 'terminal'
await screen.findByText(/previous request is no longer active/, {}, { timeout: 3000 })
@@ -2164,7 +2167,8 @@ describe('Pixel', () => {
act(()=>window.dispatchEvent(new CustomEvent('ods:pixel-select-conversation',{detail:'second_interrupted'})))
await screen.findByText('Working in this chat')
expect(fetch).toHaveBeenCalledWith('/api/pixel/chat/activity',expect.objectContaining({body:JSON.stringify({chat_id:'second_interrupted'})}))
- expect(screen.getByPlaceholderText('Message Portal...')).toBeDisabled()
+ expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
+ expect(screen.queryByTitle('Send')).toBeNull()
expect(screen.getByTitle('Stop')).toBeEnabled()
})
@@ -2290,11 +2294,11 @@ describe('Pixel', () => {
fireEvent.click(screen.getByTitle('Send'))
// During streaming the Send button is replaced by a Stop button;
- // the textarea itself is disabled.
+ // the textarea stays editable for the next message.
await waitFor(() => {
expect(screen.queryByTitle('Send')).not.toBeInTheDocument()
const ta = screen.getByPlaceholderText('Message Portal...')
- expect(ta).toBeDisabled()
+ expect(ta).toBeEnabled()
expect(screen.getByText('Working')).toBeInTheDocument()
expect(screen.getAllByText(/0:00 elapsed/).length).toBeGreaterThan(0)
expect(screen.getByText('Thinking…')).toBeInTheDocument()
diff --git a/ods/extensions/services/dashboard/src/pages/PixelAutoCompactionAcceptance.test.jsx b/ods/extensions/services/dashboard/src/pages/PixelAutoCompactionAcceptance.test.jsx
index eb66408f8..f667769c3 100644
--- a/ods/extensions/services/dashboard/src/pages/PixelAutoCompactionAcceptance.test.jsx
+++ b/ods/extensions/services/dashboard/src/pages/PixelAutoCompactionAcceptance.test.jsx
@@ -28,12 +28,13 @@ it.each(['completed','failed','runtime-restarted'])('automatic compaction read f
render(<Pixel/>);await act(async()=>{})
const field=screen.getByPlaceholderText('Message Portal...')
expect(screen.getByText('Compacting conversation context…')).toBeVisible()
- expect(field).toBeDisabled();expect(field).toHaveValue('Keep my next request')
+ // The draft stays editable while compacting; only sending waits.
+ expect(field).toBeEnabled();expect(screen.getByTitle('Send')).toBeDisabled();expect(field).toHaveValue('Keep my next request')
expect(screen.getByRole('button',{name:ring(1200)})).toBeVisible()
phase='503';await tick(2000)
expect(screen.getByText('Waiting for compaction confirmation…')).toBeVisible()
expect(screen.getByText('Checking context')).toBeVisible()
- expect(field).toBeDisabled()
+ expect(screen.getByTitle('Send')).toBeDisabled()
phase=terminal;await tick(5000)
const expected=terminal==='completed'?'Context compacted. Your full conversation is preserved.':terminal==='failed'?'Context compaction failed. Your conversation is preserved. The runtime could not complete the operation.':'Runtime restarted before compaction could be confirmed. Your conversation is preserved; you can continue.'
expect(screen.getByText(expected)).toBeVisible()
diff --git a/ods/extensions/services/dashboard/src/pages/PixelCompaction.test.jsx b/ods/extensions/services/dashboard/src/pages/PixelCompaction.test.jsx
index 7a83b34dd..bd242152e 100644
--- a/ods/extensions/services/dashboard/src/pages/PixelCompaction.test.jsx
+++ b/ods/extensions/services/dashboard/src/pages/PixelCompaction.test.jsx
@@ -138,8 +138,10 @@ it('keeps the draft and transcript while compacting and saves recovery identity
render(<Pixel/>);await screen.findByText('Available')
fireEvent.click(screen.getByRole('button',{name:'Open prompt commands'}))
fireEvent.click(screen.getByRole('button',{name:/Compact Free context/}))
- expect(screen.getByPlaceholderText('Message Portal...')).toBeDisabled()
- expect(screen.getByTitle('Start a new chat')).toBeDisabled()
+ // The draft stays editable while compacting; sending and New chat wait.
+ expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
+ expect(screen.getByTitle('Send')).toBeDisabled()
+ expect(screen.getByRole('button',{name:'New chat'})).toHaveAttribute('aria-disabled','true')
expect(stored()).toMatchObject({chatId:'context-chat',messages:initial,draft:'My next request'})
await act(async()=>finish())
await screen.findByText('Context compacted. Your full conversation is preserved.')
@@ -262,18 +264,20 @@ it.each([true,false])('resolves uncertain history only after an explicit stop an
render(<Pixel/>);await screen.findByText('Available')
const resolveButton=await screen.findByRole('button',{name:'Resolve interrupted turn'})
expect(calls('/api/pixel/chat/cancel')).toHaveLength(0)
- expect(screen.getByPlaceholderText('Message Portal...')).toBeDisabled()
+ // The draft stays editable; sending waits until the turn is resolved.
+ expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
+ expect(screen.getByTitle('Send')).toBeDisabled()
expect(screen.queryByText(/Context compaction failed/)).toBeNull()
fireEvent.click(resolveButton)
expect(resolveButton).toBeDisabled()
- expect(screen.getByTitle('Start a new chat')).toBeDisabled()
+ expect(screen.getByRole('button',{name:'New chat'})).toHaveAttribute('aria-disabled','true')
await act(async()=>finish())
if(acknowledged) {
await waitFor(()=>expect(screen.queryByRole('button',{name:'Resolve interrupted turn'})).toBeNull())
- expect(screen.getByPlaceholderText('Message Portal...')).toBeEnabled()
+ expect(screen.getByTitle('Send')).toBeEnabled()
}else {
await screen.findByText(/The stop could not be confirmed/)
- expect(screen.getByPlaceholderText('Message Portal...')).toBeDisabled()
+ expect(screen.getByTitle('Send')).toBeDisabled()
expect(screen.getByRole('button',{name:'Resolve interrupted turn'})).toBeEnabled()
}
expect(stored()).toMatchObject({chatId:'context-chat',draft:'Keep the next request',messages:initial})
diff --git a/ods/extensions/services/dashboard/src/pages/PixelComposerDeadEnds.test.jsx b/ods/extensions/services/dashboard/src/pages/PixelComposerDeadEnds.test.jsx
new file mode 100644
index 000000000..1a4d0c70e
--- /dev/null
+++ b/ods/extensions/services/dashboard/src/pages/PixelComposerDeadEnds.test.jsx
@@ -0,0 +1,289 @@
+/* global atob */
+// Dead ends seen on the demo machine: "New task" did nothing during a build,
+// a question typed then was lost, and a picture sent while Portal was busy
+// failed with a generic error. Each test drives the real composer and sidebar.
+import {act,fireEvent,screen,waitFor,within} from '@testing-library/react'
+import {render} from '../test/test-utils'
+// The repository's base ESLint profile does not mark JSX identifiers as uses.
+// eslint-disable-next-line no-unused-vars
+import Pixel from './Pixel'
+// eslint-disable-next-line no-unused-vars
+import PixelConversationNavigation from '../components/PixelConversationNavigation'
+import {OPEN_PIXEL_SEARCH} from '../components/PixelCommandSearch'
+import {sha256} from '../lib/pixelArtifacts'
+import {restoreUnsentDraft} from '../lib/pixelComposerText'
+import {busyRefusalText,isAdmissionRejected,isBusyRefusal,portalResponseFailure} from '../lib/portalResponseFailure'
+import {ATTACH_BLOCKED,newTaskBlockedReason,publishNewTaskBlocked,sendBlockedReason} from '../lib/portalTaskState'
+
+const NEW_TASK_WAITS=newTaskBlockedReason({running:true})
+const SEND_WAITS=sendBlockedReason({running:true,ready:true})
+const BUSY={error:{type:'pixel_dashboard_error',code:'image_turn_busy'}}
+const bytes=Uint8Array.from(atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aR9kAAAAASUVORK5CYII='),character=>character.charCodeAt(0))
+const imageId=`img-${'1'.repeat(32)}`,fingerprint='a'.repeat(64)
+const runtime={source:'external-host',model:'vision-model',contextLength:32768}
+const snapshot=()=>({schemaVersion:1,status:'ready',sessionRevision:'revision',context:{used:100,window:32768},
+ model:{id:'vision-model',provider:'ods-gateway',contextWindow:32768,imageInput:'supported',routeFingerprint:fingerprint},
+ compaction:{status:'idle',count:0},history:{revision:null,acknowledgedMessages:0}})
+const response=(body,status=200)=>({ok:status>=200 && status<300,status,json:async()=>body})
+const frame=value=>new TextEncoder().encode(`data: ${typeof value==='string'?value:JSON.stringify(value)}\n\n`)
+const sse=values=>{
+ const chunks=values.map(frame)
+ return {ok:true,status:200,headers:new Map([['content-type','text/event-stream']]),body:{getReader:()=>({
+ read:async()=>chunks.length?{done:false,value:chunks.shift()}:{done:true},releaseLock(){},
+ })}}
+}
+const answer=text=>sse([{choices:[{delta:{content:text}}]},'[DONE]'])
+// A build that keeps running until the test finishes it.
+function build(text='Stopwatch page ready') {
+ let finish,started=false
+ const gate=new Promise(resolve=>{finish=resolve})
+ return {finish:()=>finish(),response:{ok:true,status:200,headers:new Map([['content-type','text/event-stream']]),body:{getReader:()=>({
+ read:async()=>{
+ if(started)return {done:true}
+ started=true;await gate
+ return {done:false,value:new TextEncoder().encode(`data: ${JSON.stringify({choices:[{delta:{content:text}}]})}\n\ndata: [DONE]\n\n`)}
+ },releaseLock(){},
+ })}}}
+}
+let receipt,streams,fetchMock
+const calls=url=>fetchMock.mock.calls.filter(([called])=>called===url)
+const uploads=()=>fetchMock.mock.calls.filter(([url,options])=>url.startsWith('/api/pixel/images/') && options?.method==='POST')
+const stored=()=>JSON.parse(localStorage.getItem('ods.pixel.chat.v1'))
+const field=()=>screen.getByPlaceholderText('Message Portal...')
+const picture=()=>new File([bytes],'sketch.png',{type:'image/png'})
+async function ready(ui=<Pixel/>) {render(ui);await screen.findByText('Available')}
+async function attach() {
+ fireEvent.change(screen.getByLabelText('Choose images'),{target:{files:[picture()]}})
+ await screen.findByText(/1 × 1 · Ready/)
+}
+async function startBuild(turn) {
+ streams.push(()=>turn.response)
+ fireEvent.change(field(),{target:{value:'Build a stopwatch page'}})
+ fireEvent.click(screen.getByTitle('Send'))
+ await screen.findByTitle('Stop')
+}
+
+beforeEach(async()=>{
+ localStorage.clear()
+ publishNewTaskBlocked('')
+ HTMLDialogElement.prototype.showModal=function(){this.open=true}
+ HTMLDialogElement.prototype.close=function(){this.open=false}
+ receipt={id:imageId,sha256:await sha256(bytes),media_type:'image/png',bytes:bytes.length,width:1,height:1}
+ streams=[]
+ vi.spyOn(URL,'createObjectURL').mockReturnValue('blob:local-picture')
+ vi.spyOn(URL,'revokeObjectURL').mockImplementation(()=>{})
+ fetchMock=vi.fn(async(url,options)=>{
+ if(url==='/api/pixel/status')return response({available:true,runtime})
+ if(url==='/api/pixel/chat/context')return response(snapshot())
+ if(url==='/api/pixel/chat/stream')return (streams.shift() || (()=>answer('Done')))(options)
+ if(url.startsWith('/api/pixel/images/') && options?.method==='POST')return response(receipt,201)
+ return response({})
+ })
+ vi.stubGlobal('fetch',fetchMock)
+})
+afterEach(()=>{vi.restoreAllMocks();vi.unstubAllGlobals()})
+
+describe('pure rules', ()=>{
+ it('returns a turn that did not start to the composer without replacing newer text', ()=>{
+ expect(restoreUnsentDraft('', 'Build a stopwatch')).toBe('Build a stopwatch')
+ expect(restoreUnsentDraft(' ', 'Build a stopwatch')).toBe('Build a stopwatch')
+ expect(restoreUnsentDraft('What time is it?', 'Build a stopwatch')).toBe('Build a stopwatch\n\nWhat time is it?')
+ expect(restoreUnsentDraft('Build a stopwatch', 'Build a stopwatch')).toBe('Build a stopwatch')
+ // Restoring twice never duplicates the unsent message.
+ const once=restoreUnsentDraft('What time is it?', 'Build a stopwatch')
+ expect(restoreUnsentDraft(once, 'Build a stopwatch')).toBe(once)
+ expect(restoreUnsentDraft('Keep me', '')).toBe('Keep me')
+ })
+ it('names why New task and Send wait, and nothing when they do not', ()=>{
+ expect(NEW_TASK_WAITS).toBe('Portal is finishing the current task; you can start a new one when it’s done, or stop it.')
+ expect(newTaskBlockedReason({running:true,stopping:true})).toMatch(/stopping the current task/)
+ for(const state of ['checking','launching','compacting'])expect(newTaskBlockedReason({[state]:true})).toMatch(/in a moment/)
+ expect(newTaskBlockedReason({})).toBe('')
+ expect(SEND_WAITS).toMatch(/Your message is kept here/)
+ expect(sendBlockedReason({stopping:true,running:true,ready:true})).toMatch(/stopping/)
+ expect(sendBlockedReason({waiting:true,ready:true})).toMatch(/not ready/)
+ expect(sendBlockedReason({ready:false})).toMatch(/not ready/)
+ expect(sendBlockedReason({deleted:true,running:true})).toBe('')
+ expect(sendBlockedReason({ready:true})).toBe('')
+ })
+ it('reads a busy picture refusal calmly, as a turn that never started', ()=>{
+ expect(isBusyRefusal(BUSY.error)).toBe(true)
+ expect(isAdmissionRejected(BUSY.error)).toBe(true)
+ expect(isBusyRefusal({type:'pixel_ingress_error',code:'image_turn_busy'})).toBe(false)
+ expect(portalResponseFailure(BUSY.error)).toBe(busyRefusalText(true))
+ expect(busyRefusalText(true)).toMatch(/another picture.*did not start.*kept/)
+ for(const text of [busyRefusalText(true),busyRefusalText(false)])expect(text).not.toMatch(/could not complete|failed|error/i)
+ })
+})
+
+describe('sidebar New task', ()=>{
+ it.each([false,true])('looks disabled with the reason while Portal is busy, and a click still asks (collapsed=%s)', collapsed=>{
+ const asked=vi.fn()
+ window.addEventListener('ods:pixel-new-task',asked)
+ render(<PixelConversationNavigation collapsed={collapsed}/>)
+ const button=screen.getByRole('button',{name:'New task'})
+ expect(button).not.toHaveAttribute('aria-disabled')
+ act(()=>publishNewTaskBlocked(NEW_TASK_WAITS))
+ expect(button).toHaveAttribute('aria-disabled','true')
+ if(collapsed)expect(button).toHaveAttribute('title',NEW_TASK_WAITS)
+ else {
+ expect(button).toHaveAccessibleDescription(NEW_TASK_WAITS)
+ expect(screen.getByText(NEW_TASK_WAITS)).toBeVisible()
+ }
+ // A tap on a phone has no tooltip: the click reaches Portal, which says why.
+ fireEvent.click(button)
+ expect(asked).toHaveBeenCalledTimes(1)
+ act(()=>publishNewTaskBlocked(''))
+ expect(button).not.toHaveAttribute('aria-disabled')
+ expect(screen.queryByText(NEW_TASK_WAITS)).toBeNull()
+ window.removeEventListener('ods:pixel-new-task',asked)
+ })
+})
+
+describe('Portal during a build', ()=>{
+ it('never leaves New task inert: it waits with a reason, then starts a new chat', async()=>{
+ const turn=build()
+ await ready(<><nav aria-label="Rail"><PixelConversationNavigation collapsed={false}/></nav><Pixel/></>)
+ await startBuild(turn)
+ const rail=within(screen.getByRole('navigation',{name:'Rail'}))
+ const newTask=rail.getByRole('button',{name:'New task'})
+ expect(newTask).toHaveAttribute('aria-disabled','true')
+ expect(newTask).toHaveAccessibleDescription(NEW_TASK_WAITS)
+ expect(screen.getByRole('button',{name:'New chat'})).toHaveAttribute('aria-disabled','true')
+ expect(screen.getByRole('button',{name:'New chat'})).toHaveAttribute('title',NEW_TASK_WAITS)
+ // Clicking it anyway explains beside the composer and keeps the build open.
+ fireEvent.click(newTask)
+ expect(screen.getAllByRole('alert').some(alert=>alert.textContent===NEW_TASK_WAITS)).toBe(true)
+ expect(screen.getAllByText('Build a stopwatch page').length).toBeGreaterThan(0)
+ expect(screen.getByTitle('Stop')).toBeEnabled()
+ await act(async()=>turn.finish())
+ await screen.findByText('Stopwatch page ready')
+ await waitFor(()=>expect(newTask).not.toHaveAttribute('aria-disabled'))
+ expect(rail.queryByText(NEW_TASK_WAITS)).toBeNull()
+ fireEvent.click(newTask)
+ await screen.findByText('What do you want to work on?')
+ const conversation=within(screen.getByRole('region',{name:'Conversation messages'}))
+ expect(conversation.queryByText('Build a stopwatch page')).toBeNull()
+ // The build's chat stays in the rail, finished and ready to reopen.
+ expect(rail.getByRole('button',{name:'Build a stopwatch page'})).toBeVisible()
+ })
+
+ it('keeps the question typed during the build, saves it, and says why Enter waits', async()=>{
+ const turn=build()
+ await ready()
+ await startBuild(turn)
+ expect(field()).toBeEnabled()
+ fireEvent.change(field(),{target:{value:'What time is it in Lisbon?'}})
+ fireEvent.keyDown(field(),{key:'Enter'})
+ expect(screen.getByText(SEND_WAITS)).toBeVisible()
+ expect(field()).toHaveValue('What time is it in Lisbon?')
+ expect(calls('/api/pixel/chat/stream')).toHaveLength(1)
+ await waitFor(()=>expect(stored().draft).toBe('What time is it in Lisbon?'))
+ await act(async()=>turn.finish())
+ await screen.findByText('Stopwatch page ready')
+ expect(field()).toHaveValue('What time is it in Lisbon?')
+ await waitFor(()=>expect(screen.queryByText(SEND_WAITS)).toBeNull())
+ fireEvent.keyDown(field(),{key:'Enter'})
+ await waitFor(()=>expect(calls('/api/pixel/chat/stream')).toHaveLength(2))
+ expect(JSON.parse(calls('/api/pixel/chat/stream')[1][1].body).messages.at(-1).content).toBe('What time is it in Lisbon?')
+ })
+
+ it('inserts command search prompts into the draft and shows why New task waits there too', async()=>{
+ const turn=build()
+ await ready()
+ await startBuild(turn)
+ act(()=>window.dispatchEvent(new Event(OPEN_PIXEL_SEARCH)))
+ const search=within(screen.getByRole('dialog',{name:'Search Portal'}))
+ expect(search.getByRole('button',{name:/^New task\s*Portal is finishing the current task/})).toBeVisible()
+ fireEvent.click(search.getByRole('button',{name:/Plan deep work/}))
+ expect(field().value).toMatch(/^Build a durable plan for this goal/)
+ await act(async()=>turn.finish())
+ })
+
+ it.each(['composer','conversation'])('never lets a picture dropped on the %s replace the page, and says why it waits', async target=>{
+ const turn=build()
+ await ready()
+ await startBuild(turn)
+ const zone=target==='composer' ? field().closest('.portal-glass-composer') : screen.getByRole('region',{name:'Conversation messages'})
+ // A cancelled dragover/drop is what keeps the browser from opening the file.
+ expect(fireEvent.dragOver(zone,{dataTransfer:{types:['Files']}})).toBe(false)
+ expect(fireEvent.drop(zone,{dataTransfer:{types:['Files'],files:[picture()]}})).toBe(false)
+ expect(screen.getAllByRole('alert').some(alert=>alert.textContent===ATTACH_BLOCKED)).toBe(true)
+ expect(uploads()).toHaveLength(0)
+ await act(async()=>turn.finish())
+ await screen.findByText('Stopwatch page ready')
+ fireEvent.drop(zone,{dataTransfer:{types:['Files'],files:[picture()]}})
+ await screen.findByText(/1 × 1 · Ready/)
+ expect(uploads()).toHaveLength(1)
+ })
+
+ it('says why a pasted picture waits, without losing pasted text', async()=>{
+ const turn=build()
+ await ready()
+ await startBuild(turn)
+ const pasted=fireEvent.paste(field(),{clipboardData:{items:[{kind:'file',getAsFile:picture}]}})
+ expect(pasted).toBe(true)
+ expect(screen.getAllByRole('alert').some(alert=>alert.textContent===ATTACH_BLOCKED)).toBe(true)
+ expect(uploads()).toHaveLength(0)
+ await act(async()=>turn.finish())
+ })
+})
+
+describe('busy refusals', ()=>{
+ it('reads a busy picture refusal calmly, keeps the message and picture, and sends again in one click', async()=>{
+ streams.push(()=>sse([BUSY,'[DONE]']))
+ await ready();await attach()
+ fireEvent.change(field(),{target:{value:'Make this sketch a web page'}})
+ fireEvent.click(screen.getByTitle('Send'))
+ const notice=await screen.findByRole('status',{name:'Message not started'})
+ expect(notice).toHaveTextContent(busyRefusalText(true))
+ expect(screen.queryByText(/could not complete|Request failed|could not be received|Completion was not confirmed|Get help on Discord/)).toBeNull()
+ expect(field()).toHaveValue('Make this sketch a web page')
+ expect(screen.getByText(/1 × 1 · Ready/)).toBeVisible()
+ // The refused turn never started, so it is not left in the conversation.
+ expect(screen.getByText('What do you want to work on?')).toBeVisible()
+ await waitFor(()=>expect(stored()).toMatchObject({requestId:null,inFlight:false,interrupted:false,messages:[],draft:'Make this sketch a web page',draftImages:[receipt]}))
+ expect(calls('/api/pixel/chat/activity')).toHaveLength(0)
+ streams.push(()=>answer('Your sketch is now a page'))
+ fireEvent.click(within(notice).getByRole('button',{name:'Send again'}))
+ await screen.findByText('Your sketch is now a page')
+ const sent=JSON.parse(calls('/api/pixel/chat/stream')[1][1].body)
+ expect(sent.messages).toEqual([{role:'user',content:'Make this sketch a web page',images:[{id:imageId,sha256:receipt.sha256}]}])
+ expect(sent.history_snapshot.messages).toHaveLength(1)
+ expect(screen.queryByRole('status',{name:'Message not started'})).toBeNull()
+ await waitFor(()=>expect(screen.queryByRole('list',{name:'Attached images'})).toBeNull())
+ })
+
+ it('treats an HTTP 429 as busy, and keeps text typed while it was pending', async()=>{
+ let release
+ streams.push(()=>new Promise(resolve=>{release=()=>resolve(response({detail:'Portal image processing is busy. Try again shortly.'},429))}))
+ await ready()
+ fireEvent.change(field(),{target:{value:'Build a stopwatch page'}})
+ fireEvent.click(screen.getByTitle('Send'))
+ await screen.findByTitle('Stop')
+ fireEvent.change(field(),{target:{value:'Add a lap button too'}})
+ await act(async()=>release())
+ const notice=await screen.findByRole('status',{name:'Message not started'})
+ expect(notice).toHaveTextContent(busyRefusalText(false))
+ expect(field()).toHaveValue('Build a stopwatch page\n\nAdd a lap button too')
+ expect(screen.queryByText(/Request failed|could not be received|Completion was not confirmed|try again shortly/i)).toBeNull()
+ await waitFor(()=>expect(stored()).toMatchObject({requestId:null,inFlight:false,interrupted:false}))
+ expect(calls('/api/pixel/chat/activity')).toHaveLength(0)
+ expect(calls('/api/pixel/chat/result')).toHaveLength(0)
+ })
+
+ it('restores a busy-refused turn found after a reload, calmly and without resending it', async()=>{
+ const events=`data: ${JSON.stringify(BUSY)}\n\ndata: [DONE]\n\n`
+ localStorage.setItem('ods.pixel.chat.v1',JSON.stringify({schema:1,chatId:'busy-chat',requestId:'busy-attempt',inFlight:true,
+ messages:[{role:'user',content:'Make this sketch a web page'},{role:'assistant',content:''}]}))
+ const base=fetchMock.getMockImplementation()
+ fetchMock.mockImplementation(async(url,options)=>url==='/api/pixel/chat/result'
+ ? response({state:'rejected',events}) : base(url,options))
+ await ready()
+ await waitFor(()=>expect(field()).toHaveValue('Make this sketch a web page'))
+ await waitFor(()=>expect(stored()).toMatchObject({requestId:null,inFlight:false,interrupted:false}))
+ expect(stored().messages.at(-1).content).toBe(busyRefusalText(true))
+ expect(screen.queryByText(/could not complete|Check saved work/)).toBeNull()
+ expect(calls('/api/pixel/chat/stream')).toHaveLength(0)
+ })
+})
diff --git a/ods/extensions/services/dashboard/src/pages/PixelComposerIntegration.test.jsx b/ods/extensions/services/dashboard/src/pages/PixelComposerIntegration.test.jsx
index 9274949dd..b4d78f964 100644
--- a/ods/extensions/services/dashboard/src/pages/PixelComposerIntegration.test.jsx
+++ b/ods/extensions/services/dashboard/src/pages/PixelComposerIntegration.test.jsx
@@ -40,6 +40,7 @@ function pendingTurn() {
}
}
+// Two real turns typed key by key: a loaded full-suite run can pass 5 s.
it.each(['keyboard', 'mouse'])('allows repeated type/send turns via %s without refocusing manually', async method => {
const user = userEvent.setup()
const turns = [pendingTurn(), pendingTurn()]
@@ -53,21 +54,19 @@ it.each(['keyboard', 'mouse'])('allows repeated type/send turns via %s without r
await user.keyboard(`Question ${index + 1}`)
if (method === 'keyboard') await user.keyboard('{Enter}')
else await user.click(screen.getByRole('button', {name:'Send',exact:true}))
- await waitFor(() => expect(field).toBeDisabled())
- // jsdom keeps a disabled element focused; reproduce the browser's blur.
- field.disabled = false
- field.blur()
- field.disabled = true
- expect(field).not.toHaveFocus()
+ // The composer stays editable and focused while Portal answers.
+ await screen.findByTitle('Stop')
+ expect(field).toBeEnabled()
+ expect(field).toHaveFocus()
await act(async () => { turns[index].finish() })
- await waitFor(() => expect(field).toBeEnabled())
+ await screen.findByTitle('Send')
expect(field).toHaveFocus()
expect(field).toHaveValue('')
}
const requests = fetch.mock.calls.filter(([url]) => url === '/api/pixel/chat/stream')
expect(requests).toHaveLength(2)
expect(JSON.parse(requests[1][1].body).messages.at(-1).content).toBe('Question 2')
-})
+}, 15000)
it('keeps a search field focused when a response finishes', async () => {
const user = userEvent.setup()
@@ -77,16 +76,17 @@ it('keeps a search field focused when a response finishes', async () => {
render(<><input aria-label="Workspace search"/><Pixel/></>)
const field = await screen.findByPlaceholderText('Message Portal...')
await user.keyboard('Question{Enter}')
- await waitFor(() => expect(field).toBeDisabled())
+ await screen.findByTitle('Stop')
const search = screen.getByRole('textbox', {name:'Workspace search'})
await user.type(search, 'my file')
await act(async () => { turn.finish() })
- await waitFor(() => expect(field).toBeEnabled())
+ await screen.findByTitle('Send')
+ expect(field).toBeEnabled()
expect(search).toHaveFocus()
expect(search).toHaveValue('my file')
})
-it('restores composer focus when a request fails so the next message can be typed', async () => {
+it('keeps composer focus when a request fails so the next message can be typed', async () => {
const user = userEvent.setup()
let reject
const request = new Promise((_, rejectRequest) => { reject = rejectRequest })
@@ -95,12 +95,10 @@ it('restores composer focus when a request fails so the next message can be type
render(<Pixel/>)
const field = await screen.findByPlaceholderText('Message Portal...')
await user.keyboard('Question{Enter}')
- await waitFor(() => expect(field).toBeDisabled())
- field.disabled = false
- field.blur()
- field.disabled = true
+ await screen.findByTitle('Stop')
+ expect(field).toBeEnabled()
await act(async () => { reject(new Error('Network unavailable')) })
- await waitFor(() => expect(field).toBeEnabled())
+ await screen.findByTitle('Send')
expect(field).toHaveFocus()
await user.keyboard('Try again')
expect(field).toHaveValue('Try again')
diff --git a/ods/extensions/services/dashboard/src/pixel-workspace.css b/ods/extensions/services/dashboard/src/pixel-workspace.css
index b25fe4145..f4b096121 100644
--- a/ods/extensions/services/dashboard/src/pixel-workspace.css
+++ b/ods/extensions/services/dashboard/src/pixel-workspace.css
@@ -496,6 +496,13 @@ select option, select optgroup { background-color:rgb(var(--theme-card)); color:
.pixel-conversation-navigation { margin-top: 16px; }
.pixel-conversation-navigation .pixel-nav-item { width: 100%; min-width: 0; text-align: left; }
.pixel-conversation-navigation .pixel-nav-item span { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+/* New task waits while Portal finishes a task; its reason sits right below it.
+ A click still reaches Portal, which repeats the reason beside the composer. */
+.pixel-nav-item.rail-new-task[aria-disabled=true],
+:root .pixel-sidebar .pixel-nav-item.rail-new-task[aria-disabled=true]:hover { cursor: not-allowed; opacity: .55; color: #a7aab0; background: transparent; }
+.pixel-conversation-navigation .rail-new-task-reason { margin: 0 0 6px; padding: 0 12px 0 39px; color: #8b9097; font-size: 11px; line-height: 1.45; }
+.pixel-sidebar.is-collapsed .rail-new-task-reason { display: none; }
+@media(max-width:639px) { .pixel-sidebar .rail-new-task-reason { display: none; } }
.pixel-original-sections { padding:.6rem 0 .75rem; }
.pixel-original-sections .rail-section,.pixel-original-sections .rail-project { margin:0; padding:0; border:0; border-radius:0; background:transparent; box-shadow:none; }
.pixel-original-sections .rail-section + .rail-section { margin-top:22px; }