Merge lane-app2: the chat experience and its multi-conversation state
Integrates eight commits of reviewed chat work: the Chat destination with several conversations, markdown transcripts, tool-call chips with an expandable INPUT/OUTPUT panel, edit diff cards, the composer's stop control, and approval cards. The automated resolver failed on this merge repeatedly (its own stages kept dying on the malformed-result defect), so it was integrated by hand. Integration decisions: - Pill geometry: main's tokens win. lane-app2 carried private duplicates of DESTINATION_ITEM_SIZE/GAP and a private DESTINATION_PILL_RESERVE, added before the geometry-token migration; those duplicates are dropped in favour of the theme tokens main already exports. - IME mode: kept lane-app2's adjustResize for the window, because the chat composer and the search field both raise the keyboard and the chat UI was reviewed with it. - Protocol and view-model constants: both sides' independent additions are kept. - ChatScreen now passes the compactLabel main's SlidingPaneStack gained, and the literals lane-app2 introduced before the token discipline are converted to five new named tokens (HAIRLINE_DP, ICON_BUTTON_SMALL_DP, TOOL_PANEL_MAX_WIDTH_DP, CHAT_TITLE_MAX_WIDTH_DP, CHAT_BUBBLE_MAX_WIDTH_DP) rather than allow-listed. Verified: assembleDebug plus the full Android unit suite (409 tests) pass, including the geometry enforcement test.
This commit is contained in:
@@ -0,0 +1,285 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Approval-card scaffolding: /connect WebSocket double that pushes a permission.
|
||||
|
||||
Two sessions: `ses_perm` hands out a pending `chat_permission` after a prompt so
|
||||
the approval card can be answered (once/always/reject), and `ses_resolved` pushes
|
||||
a frame the server already settled so the card must show the outcome with no
|
||||
actions. Same wire shapes as the other stubs; test scaffolding only, never part
|
||||
of the app.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import itertools
|
||||
import json
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
|
||||
# Every prompt gets a fresh request id, so a new prompt is a new request rather
|
||||
# than a re-push of an already-answered one.
|
||||
REQUEST_SEQ = itertools.count(1)
|
||||
|
||||
PENDING_SESSION = "ses_perm"
|
||||
RESOLVED_SESSION = "ses_resolved"
|
||||
|
||||
SESSIONS = [
|
||||
{
|
||||
"id": PENDING_SESSION,
|
||||
"title": "Answer an approval",
|
||||
"agent": "build",
|
||||
"model": "deepseek-v4.1",
|
||||
"directory": "/Users/alan/repos/pipelines",
|
||||
"created_at": 1760620000000,
|
||||
"updated_at": 1760620600000,
|
||||
"busy": False,
|
||||
},
|
||||
{
|
||||
"id": RESOLVED_SESSION,
|
||||
"title": "Already resolved",
|
||||
"agent": "build",
|
||||
"model": "deepseek-v4.1",
|
||||
"directory": "/Users/alan/repos/pipelines",
|
||||
"created_at": 1760620000000,
|
||||
"updated_at": 1760620600000,
|
||||
"busy": False,
|
||||
},
|
||||
]
|
||||
|
||||
MESSAGES = {
|
||||
PENDING_SESSION: [
|
||||
{"id": "m1", "session_id": PENDING_SESSION, "role": "user",
|
||||
"parts": [{"type": "text", "id": "m1t", "text": "Refactor the layout constants."}]},
|
||||
{"id": "m2", "session_id": PENDING_SESSION, "role": "assistant",
|
||||
"parts": [{"type": "text", "id": "m2t",
|
||||
"text": "I need to edit `src/layout.kt`; approve the change to continue."}]},
|
||||
],
|
||||
RESOLVED_SESSION: [
|
||||
{"id": "r1", "session_id": RESOLVED_SESSION, "role": "user",
|
||||
"parts": [{"type": "text", "id": "r1t", "text": "Run the tests."}]},
|
||||
{"id": "r2", "session_id": RESOLVED_SESSION, "role": "assistant",
|
||||
"parts": [{"type": "text", "id": "r2t",
|
||||
"text": "The shell command was approved from another client."}]},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _recv_exact(conn, n):
|
||||
buf = b""
|
||||
while len(buf) < n:
|
||||
chunk = conn.recv(n - len(buf))
|
||||
if not chunk:
|
||||
raise EOFError
|
||||
buf += chunk
|
||||
return buf
|
||||
|
||||
|
||||
def _handshake(conn):
|
||||
data = b""
|
||||
while b"\r\n\r\n" not in data:
|
||||
chunk = conn.recv(4096)
|
||||
if not chunk:
|
||||
return False
|
||||
data += chunk
|
||||
headers = {}
|
||||
for line in data.split(b"\r\n")[1:]:
|
||||
if b":" in line:
|
||||
k, v = line.split(b":", 1)
|
||||
headers[k.strip().lower()] = v.strip()
|
||||
key = headers.get(b"sec-websocket-key")
|
||||
if not key:
|
||||
return False
|
||||
accept = base64.b64encode(hashlib.sha1(key + GUID.encode()).digest()).decode()
|
||||
conn.sendall(("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n"
|
||||
"Connection: Upgrade\r\n"
|
||||
f"Sec-WebSocket-Accept: {accept}\r\n\r\n").encode())
|
||||
return True
|
||||
|
||||
|
||||
def _read_frame(conn):
|
||||
b1, b2 = _recv_exact(conn, 2)
|
||||
opcode = b1 & 0x0F
|
||||
masked = b2 & 0x80
|
||||
length = b2 & 0x7F
|
||||
if length == 126:
|
||||
length = struct.unpack(">H", _recv_exact(conn, 2))[0]
|
||||
elif length == 127:
|
||||
length = struct.unpack(">Q", _recv_exact(conn, 8))[0]
|
||||
mask = _recv_exact(conn, 4) if masked else b""
|
||||
payload = _recv_exact(conn, length) if length else b""
|
||||
if masked:
|
||||
payload = bytes(payload[i] ^ mask[i % 4] for i in range(len(payload)))
|
||||
return opcode, payload
|
||||
|
||||
|
||||
def _frame_text(text):
|
||||
payload = text.encode()
|
||||
header = bytearray([0x81])
|
||||
n = len(payload)
|
||||
if n < 126:
|
||||
header.append(n)
|
||||
elif n < 65536:
|
||||
header.append(126)
|
||||
header += struct.pack(">H", n)
|
||||
else:
|
||||
header.append(127)
|
||||
header += struct.pack(">Q", n)
|
||||
return bytes(header) + payload
|
||||
|
||||
|
||||
def _frame_pong(payload):
|
||||
"""Answer a client ping frame (opcode 0x9) with a pong (0xA).
|
||||
|
||||
OkHttp pings on its own schedule and drops the socket when no pong comes
|
||||
back, so without this the app reconnects mid-drive.
|
||||
"""
|
||||
header = bytearray([0x8A])
|
||||
n = len(payload)
|
||||
if n < 126:
|
||||
header.append(n)
|
||||
elif n < 65536:
|
||||
header.append(126)
|
||||
header += struct.pack(">H", n)
|
||||
else:
|
||||
header.append(127)
|
||||
header += struct.pack(">Q", n)
|
||||
return bytes(header) + payload
|
||||
|
||||
|
||||
class Session:
|
||||
def __init__(self, conn):
|
||||
self.conn = conn
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def send(self, message):
|
||||
with self.lock:
|
||||
self.conn.sendall(_frame_text(json.dumps(message)))
|
||||
|
||||
def send_event(self, session_id, kind, **fields):
|
||||
frame = {"session_id": session_id, "kind": kind}
|
||||
frame.update(fields)
|
||||
self.send({"type": "chat_event", "chat_event": frame})
|
||||
|
||||
def push_permission(self, session_id, request_id, action, resources, message,
|
||||
resolved=False, decision=""):
|
||||
self.send({
|
||||
"type": "chat_permission",
|
||||
"chat_permission": {
|
||||
"session_id": session_id,
|
||||
"request_id": request_id,
|
||||
"action": action,
|
||||
"resources": resources,
|
||||
"message": message,
|
||||
"resolved": resolved,
|
||||
"decision": decision,
|
||||
"source": {"type": "tool", "message_id": "m2", "id": "call_1"},
|
||||
},
|
||||
})
|
||||
|
||||
def open_approval(self, session_id, request_id):
|
||||
self.send_event(session_id, "step", step={"status": "started", "index": 1})
|
||||
self.send_event(
|
||||
session_id,
|
||||
"text",
|
||||
message_id="m3",
|
||||
delta="Editing src/layout.kt — I need your approval before I write it.\n",
|
||||
part={"type": "text", "id": "m3t"},
|
||||
)
|
||||
self.push_permission(
|
||||
session_id,
|
||||
request_id,
|
||||
action="edit",
|
||||
resources=["src/layout.kt"],
|
||||
message="This rewrites src/layout.kt in your workspace. Review the change before allowing it.",
|
||||
)
|
||||
|
||||
|
||||
def _respond(session, request):
|
||||
kind = request.get("type")
|
||||
print(f"<- {kind}", flush=True)
|
||||
rid = request.get("id")
|
||||
if kind == "ping":
|
||||
session.send({"id": rid, "type": "pong", "time": "2026-10-16T15:00:00Z"})
|
||||
elif kind == "chat_sessions":
|
||||
session.send({"id": rid, "type": "chat_sessions", "chat_sessions": SESSIONS})
|
||||
elif kind == "chat_messages":
|
||||
body = request.get("chat_messages") or request.get("chat_query") or {}
|
||||
session_id = body.get("session_id") or PENDING_SESSION
|
||||
session.send({"id": rid, "type": "chat_messages",
|
||||
"chat_messages": MESSAGES.get(session_id, [])})
|
||||
if session_id == RESOLVED_SESSION:
|
||||
# The server reports a request it has already settled: the card must
|
||||
# state the outcome instead of offering once/always/reject.
|
||||
session.push_permission(
|
||||
session_id,
|
||||
"req_resolved",
|
||||
action="shell",
|
||||
resources=["go test ./..."],
|
||||
message="Another client already rejected this command.",
|
||||
resolved=True,
|
||||
decision="reject",
|
||||
)
|
||||
elif kind == "chat_prompt":
|
||||
body = request.get("chat_prompt") or {}
|
||||
session_id = body.get("session_id") or PENDING_SESSION
|
||||
session.send({"id": rid, "type": "chat_prompt"})
|
||||
threading.Thread(
|
||||
target=session.open_approval,
|
||||
args=(session_id, f"req_pending_{next(REQUEST_SEQ)}"),
|
||||
daemon=True,
|
||||
).start()
|
||||
elif kind == "chat_reply":
|
||||
body = request.get("chat_reply") or {}
|
||||
print(f" decision={body.get('decision')} request={body.get('request_id')}", flush=True)
|
||||
session.send({"id": rid, "type": "chat_reply"})
|
||||
elif kind == "chat_interrupt":
|
||||
session.send({"id": rid, "type": "chat_interrupt"})
|
||||
else:
|
||||
# Benign echo for pipelines/runs/status so the app's background loads do
|
||||
# not surface an error while the chat is being driven.
|
||||
session.send({"id": rid, "type": kind})
|
||||
|
||||
|
||||
def _serve(conn):
|
||||
session = Session(conn)
|
||||
try:
|
||||
if not _handshake(conn):
|
||||
return
|
||||
while True:
|
||||
opcode, payload = _read_frame(conn)
|
||||
if opcode == 0x8:
|
||||
break
|
||||
if opcode == 0x9:
|
||||
with session.lock:
|
||||
conn.sendall(_frame_pong(payload))
|
||||
continue
|
||||
if opcode != 0x1:
|
||||
continue
|
||||
try:
|
||||
request = json.loads(payload.decode())
|
||||
except Exception:
|
||||
continue
|
||||
_respond(session, request)
|
||||
except (EOFError, OSError):
|
||||
pass
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def main():
|
||||
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8799
|
||||
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
server.bind(("0.0.0.0", port))
|
||||
server.listen(8)
|
||||
print(f"chat_stub_approval listening on 0.0.0.0:{port}", flush=True)
|
||||
while True:
|
||||
conn, _ = server.accept()
|
||||
threading.Thread(target=_serve, args=(conn,), daemon=True).start()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -4304,3 +4304,662 @@ Not verified in this pass: device frames of the populated panel, the empty resul
|
||||
and a selection navigating (the visual review owns the device, per the brief's
|
||||
device policy); the panel's pure logic is exercised by the unit tests and the
|
||||
compile only.
|
||||
|
||||
## Chat destination and multiple conversations (16 Oct 2026)
|
||||
|
||||
The first Chat slice: the destination, the server session list and several
|
||||
conversations held open at once. `android/` only; no new dependency (the
|
||||
`material-icons-extended` icon is the declared one), no Pipelines server/Go/
|
||||
installer/Docker file touched, no run started from the app, and the operator's
|
||||
physical device was never used (`emulator-5556` only).
|
||||
|
||||
- **Pill.** The floating destination pill gains a Chat icon between Runs and
|
||||
Settings (icons only, 48dp targets via the named `DESTINATION_ITEM_SIZE`/
|
||||
`DESTINATION_ITEM_GAP` tokens, one non-wrapping `Row`), so it stays narrow and
|
||||
clear of the reserved 88dp bottom inset however many destinations it holds.
|
||||
The Search destination is owned by another lane and is not present on this
|
||||
base; the pill is built to take it.
|
||||
- **Brokered protocol.** `data/protocol/Chat.kt` mirrors `internal/protocol/chat.go`
|
||||
field-for-field (sessions, create, query, prompt, messages/parts, event frames,
|
||||
permission, reply); `Message` gains the optional `chat_*` payloads and
|
||||
`PipelinesClient` now forwards *unsolicited* frames (chat_event/chat_permission)
|
||||
to `events` instead of dropping them. `PipelinesRepository` exposes the typed
|
||||
chat calls.
|
||||
- **Multi-chat model.** `ui/chat/ChatStore.kt` is an Android-free state holder:
|
||||
every open chat keeps its own conversation, running flag, composer draft and
|
||||
scroll position; `open`/`activate` report when history must be (re-)fetched so
|
||||
a running session re-syncs on return instead of showing a stale copy; a
|
||||
server frame is applied to its chat whether or not it is on screen. `busy`
|
||||
sessions render read-only and the composer refuses to write to them.
|
||||
- **Surface.** `ui/chat/ChatScreen.kt` reuses the shared adaptive
|
||||
`SlidingPaneStack` (session list → conversation): the list shows each session's
|
||||
running/busy/read-only status, an open-chat strip switches between several
|
||||
conversations in one tap (with an optional X to close one), and the
|
||||
conversation is a bottom-anchored transcript of user bubbles, secondary
|
||||
reasoning, assistant text and tool-call chips that expand to INPUT
|
||||
(pretty-printed JSON) / OUTPUT (monospace, via the shared `CodeBlock`).
|
||||
"New chat" creates a server session and opens it. Closing a chat *is* provided
|
||||
(the chip X); it removes only that chat.
|
||||
- **Messages sent to a chat are optimistic** (the bubble shows immediately); the
|
||||
live delta/streaming pass is the next slice.
|
||||
|
||||
Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`,
|
||||
`ANDROID_HOME=/Users/alan/Library/Android/sdk`):
|
||||
|
||||
- `gradle :app:assembleDebug :app:testDebugUnitTest --rerun-tasks` →
|
||||
`BUILD SUCCESSFUL`, **229 tests, 0 failures** (new `MultiChatStateTest`:
|
||||
switching preserves each conversation, a running session re-syncs on return,
|
||||
drafts and scroll are per chat, a busy session is read-only, background events
|
||||
land on their own chat; new `ChatProtocolTest` for the wire shapes; new
|
||||
`ChatFormatTest`).
|
||||
- The debug APK was installed on `emulator-5556` (`FoldB_API_36`, narrow
|
||||
`wm size 1080x2340` @420) and driven with `uiautomator dump`/`input tap`;
|
||||
captures were validated with `android/scripts/capture_png.sh -s emulator-5556`:
|
||||
the pill with the Chat destination (`01_pill_chat`), the session list
|
||||
(`02_chat_list`, `05_chat_list_one_open`, `07_chat_list_two_open`), two chats
|
||||
with different conversations (`03_chat_alpha` and `06_chat_beta`), a tool chip
|
||||
expanded to INPUT/OUTPUT (`04_chat_alpha_tool_expanded`), a read-only busy
|
||||
session with a disabled composer (`08_chat_readonly`) and a per-chat draft
|
||||
preserved across a switch (`10_draft_preserved`). `adb -s emulator-5556 logcat
|
||||
-d` held 0 `FATAL EXCEPTION` and 0 `E AndroidRuntime` during the sweep.
|
||||
- **The deployed Pipelines server predates chat** (verified: a `chat_sessions`
|
||||
request answers `unknown command: chat_sessions`), and the server-side chat
|
||||
broker is a separate lane. The on-emulator sweep therefore drove the client
|
||||
against `chat_stub.py`, a minimal `/connect` WebSocket double that speaks the
|
||||
exact `internal/protocol/chat.go` JSON, so the screenshots show real client
|
||||
rendering of the documented wire contract, not the production service.
|
||||
- **APK publish.** `app-debug.apk` (18,261,008 bytes, sha256
|
||||
`aa167617c830fd7249eedf457959ef7e99b553769ed4ab82a3af6b4e8cb98ed3`) copied to
|
||||
`~/.local/share/pipelines/data/artifacts/119/1/pipelines-debug-wip-e5bde98.apk`;
|
||||
`curl -I http://10.0.0.249:8080/artifacts/119/1/pipelines-debug-wip-e5bde98.apk`
|
||||
returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
|
||||
`Content-Length: 18261008`; a streamed `GET | shasum -a 256` matched.
|
||||
|
||||
Not verified in this pass: the live brokered server (not deployed and out of
|
||||
this lane's scope), a genuinely running session's re-sync against OpenCode
|
||||
(covered by the model test, not live), and streaming/stop/approval/attachments,
|
||||
which are later slices.
|
||||
|
||||
### Review follow-ups (16 Oct 2026, implementer pass)
|
||||
|
||||
Addressing the reviewer's findings on the slice above, still `android/` only.
|
||||
|
||||
- **Shared part upsert (duplication blocker).** `ChatStore.applyDelta` and
|
||||
`applyTool` were the same message/part upsert twice. Both now call one private
|
||||
`upsertPart(frame, partId) { existing -> … }`; the delta appends to the existing
|
||||
text, the tool replaces the part, and neither can drift. `event()` and the new
|
||||
`permission()` share one `ensureThread()` placeholder creator.
|
||||
- **Diff cards (task gap).** The research report's edit view (`_CodeRun` /
|
||||
`_DiffView`, §1.3) is now reproduced: an `edit`-family tool call renders a diff
|
||||
card. `ChatFormat.toolEditDiff` derives an LCS line diff from the arguments'
|
||||
`oldString`/`newString` — the brokered protocol has **no** diff field (research
|
||||
§2.5), so it is synthesised, never silently dropped. The collapsed chip shows
|
||||
the file and the `+N -M` stat; expanding shows the green/red monospace lines
|
||||
(the app's own success/failure hues, not new literals).
|
||||
- **One read-only rule (divergent code).** `sessionReadOnly` was dead (only its
|
||||
own test called it) and disagreed with the UI's `ChatThread.readOnly = busy` for
|
||||
a locally-running busy session. The helper is deleted and `ChatThread.readOnly`
|
||||
is now `busy && !running`, the same precedence `sessionStatusLabel` uses: a turn
|
||||
we started is `Running` and writable, not read-only.
|
||||
- **`chatReply` / approval now reachable (unused API).** `observeChatEvents`
|
||||
forwards `chat_permission` into `ChatStore.permission` instead of dropping it,
|
||||
the conversation shows an approval bar (action, resources, Allow once / Always /
|
||||
Deny) and `AppViewModel.replyChatPermission` answers through `chatReply`.
|
||||
- **Stop control fixed (found while tracing read-only).** While a turn ran the
|
||||
composer's red stop button was wired to `onSend`, so it sent the draft instead
|
||||
of interrupting; it now calls `stopChat`.
|
||||
- **Evidence gap closed.** The previous checklist cited `09` (new chat) but no
|
||||
`09_*` file existed; this pass captures `09_new_chat.png` (the New-chat
|
||||
conversation), plus `11_diff_card.png` and `12_permission_bar.png` for the two
|
||||
new surfaces.
|
||||
|
||||
Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`,
|
||||
`ANDROID_HOME=/Users/alan/Library/Android/sdk`):
|
||||
|
||||
- `gradle :app:assembleDebug :app:testDebugUnitTest --offline` → `BUILD
|
||||
SUCCESSFUL`; the JUnit XML totals **233 tests, 0 failures, 0 errors, 0
|
||||
skipped** (new `toolEditDiffMarksOnlyChangedLinesAndCountsThem`,
|
||||
`toolEditDiffIsNullForNonEdits`, `locallyRunningBusyChatStaysWritable`,
|
||||
`permissionIsStoredUntilAnswered`).
|
||||
- The debug APK was installed on `emulator-5556` only and driven with
|
||||
`uiautomator dump`/`input tap`; captures validated with
|
||||
`android/scripts/capture_png.sh -s emulator-5556`: the new-chat conversation
|
||||
(`09_new_chat`), the derived diff (`11_diff_card`, showing
|
||||
`context / - val gap = 4.dp / + val gap = 6.dp / + val inset = 2.dp` under a
|
||||
`src/layout.kt +2 -1` chip) and the approval bar (`12_permission_bar`). Tapping
|
||||
**Allow once** cleared the bar through `chat_reply`. `adb -s emulator-5556
|
||||
logcat -d` held 0 `FATAL EXCEPTION` and 0 `E AndroidRuntime`. Driven against the
|
||||
test-double stub (the deployed server still predates chat).
|
||||
- **APK publish.** `app-debug.apk` (18,228,844 bytes, sha256
|
||||
`db240fc2fc295c5ab50530f9d8cefae908f307a3115b54ce9f6d713e05643b87`) copied to
|
||||
`~/.local/share/pipelines/data/artifacts/119/3/pipelines-debug-wip-e5bde98.apk`.
|
||||
|
||||
Still not verified: the live brokered server (separate lane), streaming against
|
||||
real OpenCode, and attachments — unchanged from the pass above.
|
||||
|
||||
## Conversation markdown rendering (16 Oct 2026)
|
||||
|
||||
The assistant's `text` part was rendered as one plain `Text`; it is now rendered
|
||||
as markdown, matching the reference experience (research report Part 1 §1.2).
|
||||
`android/` only; no new dependency (still just the declared
|
||||
`material-icons-extended`), no Pipelines server/Go/installer/Docker file touched,
|
||||
no run started from the app, and `emulator-5556` only (lane A's `emulator-5554`
|
||||
was never addressed).
|
||||
|
||||
- **Parser.** `ui/chat/Markdown.kt` adds a small, dependency-free CommonMark
|
||||
subset. It is pure Kotlin (no Compose, no transport) so it is unit-testable:
|
||||
paragraphs (soft-wrapped lines join with a space), `#`..`######` headings,
|
||||
fenced code (``` ``` / `~~~`, with the info string as the language), block
|
||||
quotes, bullet and ordered lists, `|` tables (with a `---` delimiter row),
|
||||
thematic rules, and inline code / bold / italic / `[label](url)` /
|
||||
bare-`http(s)://` autolinks. Underscore emphasis needs word boundaries so
|
||||
`snake_case` is never italicised. Anything outside the subset renders as plain
|
||||
text, never dropped.
|
||||
- **Renderer.** The same file turns the blocks into themed, selectable Compose
|
||||
content: fenced code reuses the shared `CodeBlock`, so the whole-block copy
|
||||
action is the existing one (label = the fence language, `code` when absent);
|
||||
tables are a bordered grid with a bold header and equal-weight wrapping cells;
|
||||
links use `LinkAnnotation.Url`, so they are tap-openable and styled from the
|
||||
scheme; inline code and headings use the shared type roles
|
||||
(`pipelinesText()`), not ad-hoc sizes. `ChatScreen.MessagePart` now calls
|
||||
`MarkdownText(part.text)` for `PART_TEXT`; the assistant message stays one
|
||||
`SelectionContainer`, so all of it remains selectable and the bounded code
|
||||
block/table keep long content inside the bubble. Geometry reuses the chat
|
||||
tokens (`CHAT_ITEM_GAP`, promoted from `private` to `internal`); only the
|
||||
quote-bar width and table border, which had no token, are new named constants.
|
||||
|
||||
Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`,
|
||||
`ANDROID_HOME=/Users/alan/Library/Android/sdk`):
|
||||
|
||||
- `gradle :app:assembleDebug :app:testDebugUnitTest --offline` → `BUILD
|
||||
SUCCESSFUL`; the JUnit XML totals **243 tests, 0 failures, 0 errors, 0
|
||||
skipped** (new `MarkdownTest`: fences keep their language, an unterminated
|
||||
fence still yields code, soft-wrapped paragraphs join, headings/rules parse by
|
||||
level, bullet/ordered lists, table header/rows, inline code/bold/italic/link,
|
||||
bare-URL autolink trims trailing punctuation, `snake_case` is not emphasis,
|
||||
empty source → no blocks).
|
||||
- The debug APK was installed on `emulator-5556` only and driven against a
|
||||
stdlib `/connect` WebSocket double serving a fixed history; capture was
|
||||
validated with `android/scripts/capture_png.sh -s emulator-5556`:
|
||||
`chat_markdown_conversation.png` shows the bottom-anchored transcript with the
|
||||
user bubble, the secondary reasoning line, body markdown with inline code and
|
||||
an underlined link, a `kotlin` fenced code block with its copy action, and the
|
||||
bordered `Surface | Role` table. `adb -s emulator-5556 logcat -d` held 0
|
||||
`FATAL EXCEPTION` and 0 `E AndroidRuntime` during the sweep.
|
||||
- **APK publish.** `app-debug.apk` (18,076,412 bytes, sha256
|
||||
`bb290a7f42a3b28e613098dfffea438c34a5332081cffc6a2fbc0d275c207f68`) copied to
|
||||
`~/.local/share/pipelines/data/artifacts/124/1/pipelines-debug-wip-0718f5b.apk`;
|
||||
`HEAD` is `0718f5b` and a streamed `curl | shasum -a 256` of
|
||||
`http://10.0.0.249:8080/artifacts/124/1/pipelines-debug-wip-0718f5b.apk`
|
||||
matched.
|
||||
|
||||
Not verified: the live brokered server (separate lane), streaming against real
|
||||
OpenCode, and attachments — unchanged from the passes above. The markdown subset
|
||||
is intentionally smaller than full CommonMark (no HTML, no reference links, no
|
||||
nested lists, no strikethrough).
|
||||
|
||||
## Streaming replies (16 Oct 2026)
|
||||
|
||||
The live delta/streaming pass promised by the first slice. `android/` only; no new
|
||||
dependency (still just the declared `material-icons-extended`), no Pipelines
|
||||
server/Go/installer/Docker file touched, no run started from the app, and
|
||||
`emulator-5556` only (lane A's `emulator-5554` was never addressed).
|
||||
|
||||
- **Turn lifecycle in the model.** `ChatStore` now owns `ChatThread.runningSince`
|
||||
and one private `setRunning` transition, so a turn that begins is stamped with
|
||||
the wall clock and settling clears it; `ChatThread.elapsedMillis(now)` is the one
|
||||
pure derivation the indicator and its test share. `event` already appended
|
||||
`text`/`reasoning` deltas to the target part and upserted tool parts, wherever the
|
||||
frame's chat sits in the open order.
|
||||
- **Running indicator.** The transcript's indicator shows the spinner, `Working…`
|
||||
and the live elapsed time (ticked once a second, never per frame, through the
|
||||
shared `formatDuration`). Its tick loop is keyed on the turn's start and stops the
|
||||
moment the turn settles, and the elapsed value keeps counting across a chat
|
||||
switch because it lives on the thread, not the composable.
|
||||
- **Follow the stream.** The transcript hard-jumps to the newest item while a turn
|
||||
runs — a fast-growing reply outruns an animation — unless the operator has
|
||||
scrolled up to read; returning to the end resumes following. Consuming the list
|
||||
state's `interactionSource.interactions` (`DragInteraction.Start`/`Stop`/`Cancel`)
|
||||
distinguishes a user drag from the programmatic jump, so the jump never un-sticks
|
||||
the view.
|
||||
- **Reconnect resync.** `AppViewModel.observeConnection` re-fetches every open
|
||||
chat's history whenever the socket transitions to `Connected`, after
|
||||
`ChatStore.streamResumed()` settles each running thread (a still-live stream
|
||||
re-asserts `running` on its next frame, so no stale `Working…` sticks). The
|
||||
resync *replaces* the conversation wholesale, so a gap can neither duplicate nor
|
||||
drop text.
|
||||
- **Failure settle.** A server-pushed `error` frame carries no session id (the
|
||||
brokered protocol cannot attribute it), so `ChatStore.streamError` settles the
|
||||
sole running chat — or the active one when several are in flight — and keeps the
|
||||
server's text; with nothing running it is ignored. The prompt-call failure path
|
||||
already settled the turn and is unchanged.
|
||||
- **Non-blocking.** Unsolicited frames reach the UI through the client's bounded
|
||||
`SharedFlow` (`tryEmit` from the socket thread, `DROP_OLDEST` capacity 256), so a
|
||||
slow collector never blocks the read loop; each mutation touches only its chat and
|
||||
the `LazyColumn` keys limit recomposition to the changed item.
|
||||
|
||||
Evidence (macOS, JDK 17 target, Gradle 9.7.1,
|
||||
`ANDROID_HOME=/Users/alan/Library/Android/sdk`):
|
||||
|
||||
- `gradle :app:assembleDebug :app:testDebugUnitTest` → `BUILD SUCCESSFUL`; the JUnit
|
||||
XML totals **248 tests, 0 failures, 0 errors, 0 skipped** (new `ChatStreamTest`:
|
||||
a delta sequence grows the rendered text and toggles the running indicator, the
|
||||
elapsed time comes from the turn's own start and a repeated start keeps it,
|
||||
`streamResumed` settles every open chat and returns them for re-fetch,
|
||||
`streamError` settles the running turn with the server's text and is ignored with
|
||||
nothing running).
|
||||
- The debug APK was installed on `emulator-5556` only and driven with
|
||||
`uiautomator dump`/`input tap` against `.stream_check/stream_stub.py` (a stdlib
|
||||
`/connect` WebSocket double that streams `chat_event` frames; test scaffolding,
|
||||
not the app — the deployed server still predates chat). Captures were validated
|
||||
with `android/scripts/capture_png.sh -s emulator-5556`: a mid-stream reply with
|
||||
the growing transcript and the indicator at `Working… · 1s`
|
||||
(`chat_stream_01_early`) and `Working… · 4s` with the list followed to the newest
|
||||
line (`chat_stream_02_mid`); the settled turn with the completed `bash 340ms`
|
||||
tool chip, no indicator and the send control restored (`chat_stream_03_settled`);
|
||||
and, after a mid-stream drag up, the transcript **staying** where the operator
|
||||
left it while the turn still ran (`chat_stream_04_scrolled_up`). `adb -s
|
||||
emulator-5556 logcat -d` held 0 `FATAL EXCEPTION` and 0 `E AndroidRuntime`
|
||||
during the sweep.
|
||||
- **APK publish.** `app-debug.apk` (18,262,465 bytes, sha256
|
||||
`ef435b662e6f7e7467b5ae25b69fb24f8904334af204224aad00bfd76879a84e`) copied to
|
||||
`~/.local/share/pipelines/data/artifacts/126/1/pipelines-debug-wip-d7f6500.apk`;
|
||||
`curl -I http://10.0.0.249:8080/artifacts/126/1/pipelines-debug-wip-d7f6500.apk`
|
||||
returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
|
||||
`Content-Length: 18262465`, and a streamed `GET | shasum -a 256` matched.
|
||||
|
||||
Not verified in this pass: the live brokered server (separate lane), streaming
|
||||
against real OpenCode, and attachments — unchanged. `:app:lintDebug` could not run
|
||||
in this environment: the Gradle JVM reports `25.0.4.1`, a version string the AGP
|
||||
8.7.2 lint (IntelliJ `JavaVersion`) rejects, so lint fails before analysing the
|
||||
tree; this is environmental and unrelated to the change.
|
||||
|
||||
## Tool-call chips and the expandable panel (16 Oct 2026)
|
||||
|
||||
The tool-call surface now matches the reference chat's `_ToolCalls`/`_ToolChip`
|
||||
and `_buildPanel` (research §1.3) more closely. `android/` only; no new
|
||||
dependency (still just the declared `material-icons-extended`), no Pipelines
|
||||
server/Go/installer/Docker file touched, no run started from the app, and
|
||||
`emulator-5556` only (lane A's `emulator-5554` was never addressed).
|
||||
|
||||
- **Grouped chips.** A run of consecutive `tool` parts in one assistant turn is
|
||||
now one `FlowRow` of compact chips (`ToolCalls`/`ToolChip`), so the turn's calls
|
||||
sit together and wrap instead of each taking a full-width row. Each chip keeps
|
||||
its kind icon, label (the edited file for an `edit`), `+N -M` diff stat,
|
||||
duration and running spinner.
|
||||
- **Overlay panel, scroll preserved.** Tapping a chip opens its INPUT/OUTPUT
|
||||
panel as a `Popup` anchored to that chip, not as inline content. The former
|
||||
inline panel re-flowed the transcript (a short chat visibly jumped); the popup
|
||||
is outside the list layout, so opening, failing or dismissing it never moves the
|
||||
conversation's scroll anchor. `ToolPanelPositionProvider` places it below the
|
||||
chip, flips it above when there is no room, and keeps it inside the window
|
||||
margins. The panel is dismissible by its own X or by tapping outside, and its
|
||||
INPUT and OUTPUT blocks carry the shared `CodeBlock` copy action.
|
||||
- **Visible failure.** An `error` tool call is now unmistakable: an
|
||||
error-tinted chip with an `ErrorOutline` icon (`toolFailed`), and its panel
|
||||
shows an ERROR block with the tool's error text (`ChatFormat.toolFailed`).
|
||||
- **Diff cards preserved.** An `edit`-family chip still expands to the synthesised
|
||||
green/red diff (`toolEditDiff`/`DiffView`), unchanged.
|
||||
|
||||
Evidence (macOS, Gradle 9.7.1 `--offline`, `ANDROID_HOME=/Users/alan/Library/Android/sdk`):
|
||||
|
||||
- `gradle :app:assembleDebug :app:testDebugUnitTest --offline` → `BUILD
|
||||
SUCCESSFUL`; the JUnit XML totals **252 tests, 0 failures, 0 errors, 0
|
||||
skipped** (new `toolFailedOnlyForTheErrorStatus`, and
|
||||
`ToolPanelPositionProviderTest`: below-the-chip, flip-above and margin-clamp
|
||||
placement).
|
||||
- The debug APK was installed on `emulator-5556` only and driven against
|
||||
`.tool_calls_check/chat_stub_tools.py` (a stdlib `/connect` WebSocket double
|
||||
serving the documented `internal/protocol/chat.go` JSON; test scaffolding, not
|
||||
the app). Captures were validated with `android/scripts/capture_png.sh -s
|
||||
emulator-5556`: `01_tools_collapsed.png` (the completed `bash 340ms` and
|
||||
`src/layout.kt +2 -2 300ms` chips grouped), `02_tools_expanded.png` (the bash
|
||||
chip expanded to INPUT pretty JSON + OUTPUT monospace with the transcript behind
|
||||
it unmoved — the chips keep the same on-screen position), and
|
||||
`03_error_chip_collapsed.png`/`04_error_chip_expanded.png` (the failed `shell`
|
||||
chip in the error container and its panel INPUT + ERROR text). Tapping outside
|
||||
the panel dismissed it with the chips still in place. `adb -s emulator-5556
|
||||
logcat -d` held 0 `FATAL EXCEPTION` and 0 `E AndroidRuntime` during the sweep.
|
||||
- **APK publish.** `app-debug.apk` (18,262,465 bytes, sha256
|
||||
`160f10ea8a2dc80364bb7f38596d50d08557ccce01f99705b93a8b9bc9216c27`) copied to
|
||||
`~/.local/share/pipelines/data/artifacts/129/1/pipelines-debug-wip-d7f6500.apk`;
|
||||
`curl -I http://10.0.0.249:8080/artifacts/129/1/pipelines-debug-wip-d7f6500.apk`
|
||||
returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
|
||||
`Content-Length: 18262465`, and a streamed `GET | shasum -a 256` matched.
|
||||
|
||||
Not verified in this pass: the live brokered server (separate lane), streaming
|
||||
against real OpenCode, and attachments — unchanged from the passes above.
|
||||
|
||||
## Tool-call review fixes (16 Oct 2026)
|
||||
|
||||
Two findings from the tool-call slice review, both in `android/`, under the same
|
||||
constraints as above (no new dependency beyond the declared
|
||||
`material-icons-extended`, no Pipelines server/Go/installer/Docker file touched,
|
||||
no run started from the app, `emulator-5556` only).
|
||||
|
||||
- **One elapsed derivation.** `ChatScreen.rememberElapsedMillis` re-derived the
|
||||
running turn's elapsed time by subtracting the start itself, duplicating the
|
||||
tested `ChatThread.elapsedMillis` and contradicting the two KDocs that claimed
|
||||
the indicator shared the model's derivation. The composable now ticks a
|
||||
`rememberElapsedNow(runningSince)` wall clock (once a second, and only while
|
||||
the turn lives) and reads `thread.elapsedMillis(now)`, so the model and the UI
|
||||
cannot drift.
|
||||
- **No per-frame allocation.** `ToolCalls` keyed its open-panel `remember` on
|
||||
`parts.map { it.id }`, allocating a list on every streaming recomposition. The
|
||||
key is unnecessary — an id no longer among the calls simply matches nothing —
|
||||
so `openId` is plain remembered state and a streaming rebuild no longer
|
||||
allocates a key list.
|
||||
|
||||
Evidence (macOS, Gradle 9.7.1 `--offline`,
|
||||
`ANDROID_HOME=/Users/alan/Library/Android/sdk`):
|
||||
|
||||
- `gradle :app:assembleDebug :app:testDebugUnitTest --offline` → `BUILD
|
||||
SUCCESSFUL`; the JUnit XML totals **252 tests, 0 failures, 0 errors, 0
|
||||
skipped**.
|
||||
- The rebuilt debug APK was installed on `emulator-5556` only and driven against
|
||||
`.tool_calls_check/chat_stub_tools.py` and `chat_stub_error.py` (stdlib
|
||||
`/connect` WebSocket doubles serving the documented `internal/protocol/chat.go`
|
||||
JSON; test scaffolding, not the app). Captures were validated with
|
||||
`android/scripts/capture_png.sh -s emulator-5556` into `.tool_calls_fix/`:
|
||||
`01_tools_collapsed.png` (the completed `bash 340ms` and `src/layout.kt +2 -2
|
||||
300ms` chips grouped), `02_tools_expanded.png` (the bash chip's INPUT pretty
|
||||
JSON + OUTPUT monospace), `04_diff_card.png` (the edit chip's synthesised
|
||||
green/red diff card), `03_dismissed_outside.png` (tapping outside dismissed the
|
||||
panel with both chips at the same on-screen bounds), and
|
||||
`05_error_chip_collapsed.png`/`06_error_chip_expanded.png` (the failed `shell`
|
||||
chip in the error container, with a `Failed tool call` description, and its
|
||||
panel INPUT + ERROR text). `adb -s emulator-5556 logcat -d` held 0 `FATAL
|
||||
EXCEPTION` and 0 `E AndroidRuntime` during the sweep.
|
||||
- **APK publish.** `app-debug.apk` (18,219,766 bytes, sha256
|
||||
`b607a879ce2f2ac324fe6fa254918a456337c678abc1781bb79a05d88d539984`) copied to
|
||||
`~/.local/share/pipelines/data/artifacts/129/3/pipelines-debug-wip-d7f6500.apk`;
|
||||
`curl -I http://10.0.0.75:8080/artifacts/129/3/pipelines-debug-wip-d7f6500.apk`
|
||||
returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
|
||||
`Content-Length: 18219766`, and a streamed `GET | shasum -a 256` matched. This
|
||||
supersedes the `129/1` publish above: it is built from the current source, so
|
||||
the change is in the served artifact (a fresh rebuild can still differ in
|
||||
`classes5.dex` — the reproducibility caveat recorded in review stands).
|
||||
|
||||
Not verified in this pass: the live brokered server (separate lane), streaming
|
||||
against real OpenCode, and attachments — unchanged from the passes above.
|
||||
`:app:lintDebug` still cannot run here (the Gradle JVM's `25.0.4.1` version
|
||||
string is rejected by AGP 8.7.2 lint), unchanged from the slice above.
|
||||
|
||||
## Tool-call review fixes, second pass (16 Oct 2026)
|
||||
|
||||
Three findings from the tool-call slice's second review, all in `android/` under
|
||||
the same constraints (no new dependency beyond the declared
|
||||
`material-icons-extended`, no Pipelines server/Go/installer/Docker file touched, no
|
||||
run started from the app, `emulator-5556` only).
|
||||
|
||||
- **A failed edit call shows its error.** The panel only rendered the diff for an
|
||||
`edit`-family call, because the `diff != null` branch sat above the `failed`
|
||||
check, so a *failed* edit showed no error text. The ERROR block is now emitted
|
||||
whenever `toolFailed`, alongside the diff when one exists; a failed non-edit call
|
||||
keeps INPUT + ERROR, and a successful edit still shows the diff alone.
|
||||
- **The error message, not the partial output.** `ChatFormat.toolOutputText`
|
||||
returned non-blank `state.content` before it considered `state.error`, and that
|
||||
text fed the ERROR block, so a failed call carrying both showed its partial
|
||||
output under the ERROR heading. The failed call's text now comes from the new
|
||||
`toolErrorText`, which prefers the server's message and falls back to the output
|
||||
text only when the failure carries none; `toolOutputText` is the OUTPUT
|
||||
derivation again.
|
||||
- **README mechanism corrected.** The follow-the-stream bullet claimed a
|
||||
`snapshotFlow` on the list's scroll state; the code consumes
|
||||
`listState.interactionSource.interactions` (`DragInteraction.Start`/`Stop`/`Cancel`),
|
||||
as the bullet now says.
|
||||
|
||||
Evidence (macOS, Gradle 9.7.1, `ANDROID_HOME=/Users/alan/Library/Android/sdk`):
|
||||
|
||||
- `gradle :app:testDebugUnitTest :app:assembleDebug` → `BUILD SUCCESSFUL`; the
|
||||
JUnit XML totals **253 tests, 0 failures, 0 errors, 0 skipped** (the failed-text
|
||||
helper split into `toolOutputFallsBackToNoOutput` and
|
||||
`toolErrorPrefersTheMessageOverPartialOutput`, which asserts the message wins over
|
||||
a failed call's partial output).
|
||||
- The rebuilt debug APK was installed on `emulator-5556` only and driven against
|
||||
`.tool_calls_fix2/chat_stub_failed_edit.py` (the review tool stub plus a failed
|
||||
`edit` call with `oldString`/`newString` and a failed `bash` call carrying both
|
||||
partial output and an error; stdlib `/connect` WebSocket double, test
|
||||
scaffolding, not the app). Captures were validated with
|
||||
`android/scripts/capture_png.sh -s emulator-5556` into `.tool_calls_fix2/`:
|
||||
`04_failed_edit_expanded.png` shows the failed edit chip's diff *and* its ERROR
|
||||
block (`oldString not found in src/layout.kt`), and
|
||||
`06_failed_bash_expanded.png` shows the failed bash call's INPUT + ERROR
|
||||
(`exit status 2: src/nope.kt: No such file`), the error text — not the partial
|
||||
output — under the ERROR heading. `uiautomator dump` confirms the same nodes;
|
||||
`adb -s emulator-5556 logcat -d` held 0 `FATAL EXCEPTION` and 0 `E
|
||||
AndroidRuntime` during the sweep.
|
||||
- **APK publish.** `app-debug.apk` (18,219,360 bytes, sha256
|
||||
`4522aa62c8a3a59033aa2cca8b7fba65267dbdde473284585eaae47f03aeda2f`) copied to
|
||||
`~/.local/share/pipelines/data/artifacts/129/5/pipelines-debug-wip-d7f6500.apk`;
|
||||
`curl -I http://10.0.0.249:8080/artifacts/129/5/pipelines-debug-wip-d7f6500.apk`
|
||||
returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
|
||||
`Content-Length: 18219360`, and a streamed `GET | shasum -a 256` matched. This
|
||||
supersedes the `129/3` publish above: it is rebuilt from the current source, so
|
||||
the fix is in the served artifact (the `classes5.dex` reproducibility caveat
|
||||
recorded in review stands).
|
||||
|
||||
Not verified in this pass: the live brokered server (separate lane), streaming
|
||||
against real OpenCode, and attachments — unchanged from the passes above.
|
||||
|
||||
## Edit diffs: file name, stat and large-edit summarisation (16 Oct 2026)
|
||||
|
||||
The edit diff card already derived its lines, but three things the task calls for
|
||||
were missing or wrong. `android/` only; no new dependency (still just the declared
|
||||
`material-icons-extended`), no Pipelines server/Go/installer/Docker file touched,
|
||||
no run started from the app, and `emulator-5556` only (lane A's `emulator-5554`
|
||||
was never addressed).
|
||||
|
||||
- **The file name and `+N -M` are on the card, not just the chip.** The expanded
|
||||
panel header showed the tool name (`edit`); it now shows the edited file (as the
|
||||
chip already did) and the shared green/red `DiffStat`, so the diff names its file
|
||||
and its counts wherever it is read.
|
||||
- **Very large edits are summarised, not flooded.** A diff longer than
|
||||
`MAX_RENDERED_DIFF_LINES` (200) kept *every* line — the >400-line fallback
|
||||
rendered `old + new` in full, thousands of `Text` nodes in a scrolling `Column`
|
||||
on a phone. `ChatFormat.toolEditDiff` now keeps the first 200 lines and carries
|
||||
the rest in the new `ToolDiff.omitted`; `DiffView` prints
|
||||
`… N more changed lines not shown` **first**, so the truncation is visible
|
||||
without scrolling. The `+N -M` counts still describe the whole edit, never the
|
||||
rendered prefix.
|
||||
|
||||
Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`,
|
||||
`ANDROID_HOME=/Users/alan/Library/Android/sdk`):
|
||||
|
||||
- `gradle :app:testDebugUnitTest :app:assembleDebug` → `BUILD SUCCESSFUL`; the
|
||||
JUnit XML totals **254 tests, 0 failures, 0 errors, 0 skipped** (new
|
||||
`toolEditDiffSummarisesAnOversizedEditInsteadOfRenderingEveryLine`, which
|
||||
asserts the true `+250 -250` counts, the 200-line render cap and
|
||||
`omitted = 300`; the small-edit test now also pins `omitted = 0`).
|
||||
- The rebuilt debug APK was installed on `emulator-5556` only and driven against
|
||||
`.diff_check/chat_stub_diff.py` (the `.tool_calls_check/chat_stub_tools.py`
|
||||
`/connect` WebSocket double plus a 300-line edit whose intersection with the
|
||||
cap must summarise; stdlib double, test scaffolding, not the app). Captures were
|
||||
validated with `android/scripts/capture_png.sh -s emulator-5556`:
|
||||
`03_diff_small.png` shows the small edit card — `src/layout.kt +2 -2 300ms`,
|
||||
then red `- val gap = 4.dp` / `- val inset = 1.dp` and green
|
||||
`+ val gap = 6.dp` / `+ val inset = 2.dp` in monospace — and
|
||||
`05_diff_summarised.png` shows `src/big.kt +100 -100 150ms` over
|
||||
`… 200 more changed lines not shown` and the interleaved context/`-`/`+` lines.
|
||||
`uiautomator dump` confirms the same nodes; `adb -s emulator-5556 logcat -d`
|
||||
held 0 `FATAL EXCEPTION` and 0 `E AndroidRuntime` during the sweep.
|
||||
- **APK publish.** `app-debug.apk` (18,220,501 bytes, sha256
|
||||
`7cfca9c40361d4f1871bc61da20aec8c918637f8e085b8eb534d134b3cb8fe00`) copied to
|
||||
`~/.local/share/pipelines/data/artifacts/133/1/pipelines-debug-wip-291cec2.apk`;
|
||||
`curl -I http://10.0.0.75:8080/artifacts/133/1/pipelines-debug-wip-291cec2.apk`
|
||||
returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
|
||||
`Content-Length: 18220501`, and a streamed `GET | shasum -a 256` matched.
|
||||
|
||||
Not verified in this pass: the live brokered server (separate lane), streaming
|
||||
against real OpenCode, and attachments — unchanged from the passes above.
|
||||
`:app:lintDebug` still cannot run here (the Gradle JVM's `25.0.4.1` version
|
||||
string is rejected by AGP 8.7.2 lint), unchanged from the slices above.
|
||||
|
||||
## Stopping a running turn (16 Oct 2026)
|
||||
|
||||
The composer already swapped its send control for a red `Icons.stop` while a turn
|
||||
ran and `AppViewModel.stopChat` already sent `chat_interrupt`; the slice was
|
||||
missing the proof the task asks for — a unit test pinning the interrupt frame —
|
||||
so this pass adds that seam and the on-device capture. `android/` only; no new
|
||||
dependency (still just the declared `material-icons-extended`), no Pipelines
|
||||
server/Go/installer/Docker file touched, no run started from the app, and
|
||||
`emulator-5556` only (lane A's `emulator-5554` was never addressed).
|
||||
|
||||
- **One interrupt frame.** `ChatProtocol.interruptRequest(sessionId)` builds the
|
||||
single `chat_interrupt` frame (a `ChatQuery` carrying the session id);
|
||||
`PipelinesRepository.chatInterrupt` sends it, so the wire shape is no longer
|
||||
constructed inline where only production can see it.
|
||||
- **The stopped state is honest.** On a successful interrupt the thread settles
|
||||
(`running = false`, no error) and the composer's send control returns; only a
|
||||
failing call (or a server-pushed error frame) sets the conversation's error, so
|
||||
a stop the server accepted is never shown as a failure.
|
||||
|
||||
Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`,
|
||||
`ANDROID_HOME=/Users/alan/Library/Android/sdk`):
|
||||
|
||||
- `gradle :app:assembleDebug :app:testDebugUnitTest --offline` → `BUILD
|
||||
SUCCESSFUL`; the JUnit XML totals **255 tests, 0 failures, 0 errors, 0
|
||||
skipped** (new `chatInterruptRequestCarriesTheRunningSession`, which asserts the
|
||||
frame the stop control sends is `chat_interrupt` for the running session and
|
||||
survives the client's JSON round-trip).
|
||||
- The debug APK was installed on `emulator-5556` only and driven against
|
||||
`.stop_check/chat_stub_hold.py` (a stdlib `/connect` WebSocket double that holds
|
||||
the turn open until `chat_interrupt`; test scaffolding, not the app) with
|
||||
`uiautomator dump`/`input tap`; captures validated with
|
||||
`android/scripts/capture_png.sh -s emulator-5556`:
|
||||
`stop_control_running.png` shows the running turn (`Working… · 11s`) with the
|
||||
composer's send control replaced by the red stop control (bottom-right, in thumb
|
||||
reach) and the top-bar stop action; `stop_control_stopped.png` shows the same
|
||||
chat after the stop was pressed — the indicator gone, the send control back, and
|
||||
no error text (the server acknowledged the interrupt). The stub log recorded
|
||||
exactly one `chat_interrupt`. `adb -s emulator-5556 logcat -d` held 0
|
||||
`FATAL EXCEPTION` and 0 `E AndroidRuntime` during the sweep.
|
||||
- **APK publish.** `app-debug.apk` (18,240,566 bytes, sha256
|
||||
`56abfb2c59a9c09fabbe32d7de4f0164cdc852cece4b7df3655dd0c233256248`) copied to
|
||||
`~/.local/share/pipelines/data/artifacts/135/1/pipelines-debug-wip-e2f306b.apk`;
|
||||
`curl -I http://10.0.0.249:8080/artifacts/135/1/pipelines-debug-wip-e2f306b.apk`
|
||||
returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
|
||||
`Content-Length: 18240566`, and a streamed `GET | shasum -a 256` matched.
|
||||
|
||||
### Follow-up: one tested composer action (16 Oct 2026, run 143)
|
||||
|
||||
The stop control was still chosen by an inline `if (thread.running)` in the
|
||||
composer, and the text field's keyboard send action only checked `canSend`, so a
|
||||
prompt could still be sent from the IME while a turn was in flight even though the
|
||||
visible control had become stop. `ChatFormat.composerAction(thread)`
|
||||
(`ComposerAction.Send`/`Stop`) is now the single pure derivation the trailing
|
||||
button and the keyboard action both read, so the two controls can no longer
|
||||
disagree; `ChatFormatTest.composerControlIsStopWhileARunIsInFlightAndSendOtherwise`
|
||||
covers it. `android/` only; no new dependency.
|
||||
|
||||
- Re-verified: `gradle :app:assembleDebug :app:testDebugUnitTest --offline` →
|
||||
`BUILD SUCCESSFUL`, **266 tests, 0 failures** (the new composer-action case).
|
||||
- **APK publish.** `app/build/outputs/apk/debug/app-debug.apk` (18,249,033 bytes,
|
||||
sha256 `a9ce0cc8829513ee37fa5abaafa765307d5574f7cbd2b9cf0bc32392d0c1461e`) copied
|
||||
to `~/.local/share/pipelines/data/artifacts/143/1/pipelines-debug-wip-609721d.apk`.
|
||||
`curl -I http://10.0.0.249:8080/artifacts/143/1/pipelines-debug-wip-609721d.apk`
|
||||
returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
|
||||
`Content-Length: 18249033`; a streamed `GET | shasum -a 256` matched.
|
||||
- Not driven on a device in this pass: the constraint that the stop control be
|
||||
exercised on an emulator only conflicts with this run's device note that only the
|
||||
operator's Pixel (adb serial `58281FDCG000JF`) is available and no emulator may be
|
||||
run, so the evidence here is the unit tests and the build rather than a fresh
|
||||
screenshot. The earlier `emulator-5556` captures
|
||||
(`.stop_check/stop_control_running.png`, `.stop_check/stop_control_stopped.png`)
|
||||
still show the running/stopped control states.
|
||||
|
||||
Not verified in this pass: the live brokered server (separate lane), streaming
|
||||
against real OpenCode, and attachments — unchanged from the passes above.
|
||||
|
||||
## Approvals in the conversation, answered in place (16 Oct 2026)
|
||||
|
||||
The brokered protocol already carried `chat_permission`, but the phone only showed
|
||||
it as a bar above the composer and removed it the moment it was answered. This
|
||||
pass makes a pushed approval a card in the conversation: the reference app's amber
|
||||
risk framing, once/always/reject actions wired to `chat_reply`, an in-place settle
|
||||
on answer, and a resolved state for a request the server reports as already
|
||||
settled. `android/` only; no new dependency (still just the declared
|
||||
`material-icons-extended`), no Pipelines server/Go/installer/Docker file touched,
|
||||
no run started from the app, and `emulator-5556` only (lane A's `emulator-5554`
|
||||
was never addressed).
|
||||
|
||||
- **The card is in the transcript.** `ApprovalCardItem` is the transcript's last
|
||||
item, so the request sits with the conversation rather than floating above the
|
||||
composer. It shows the action (`Approve edit`), the affected resources in
|
||||
monospace, the amber `RISK REVIEW` panel carrying the server's risk summary
|
||||
(falling back to a neutral sentence naming the action when the server sends
|
||||
none), and `Allow once` / `Always allow` / `Reject`. The amber `tertiary` role
|
||||
at 12% fills the review panel and its shield glyph, and at 50% outlines a
|
||||
pending card — the same amber `shield_outlined` framing the reference app uses.
|
||||
Geometry reuses the existing chat tokens; the only new constants are the two
|
||||
alpha strengths.
|
||||
- **Findable without scrolling the whole chat.** The conversation's top bar shows
|
||||
a gold `PanTool` "Waiting for your approval" action while a request is open;
|
||||
tapping it jumps the transcript to the card, and the same glyph marks the chat's
|
||||
chip in the open-chat strip. A newly arrived request is also scrolled into view
|
||||
by the existing bottom-follow, and the running indicator stands down while the
|
||||
turn waits (the clock would otherwise tick on work that is not happening).
|
||||
- **Answered in place.** `ChatStore.answerPermission` records the decision
|
||||
optimistically, so the card settles to `Allowed once` / `Always allowed` /
|
||||
`Rejected` and drops its actions instead of disappearing; a failed `chat_reply`
|
||||
reopens the same request (`permissionReplyFailed`) with the error, so a decision
|
||||
the server never received is never shown as accepted. `ChatProtocol.replyRequest`
|
||||
is the one builder `PipelinesRepository.chatReply` sends, so the card's actions
|
||||
and the wire frame cannot drift.
|
||||
- **Already resolved is honest.** `ChatPermissionFrame` gained optional `resolved`
|
||||
and `decision` fields. A frame for a request the server reports as settled
|
||||
renders as `Rejected`/`Always allowed`/`Already resolved` with no controls, so a
|
||||
stale once/always/reject is never offered for a closed request; a frame for a
|
||||
new request replaces a settled card. Those fields are the additive contract the
|
||||
server sends when it reports an already-settled request (both are omitted by an
|
||||
older peer, which simply leaves every request pending).
|
||||
|
||||
Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`,
|
||||
`ANDROID_HOME=/Users/alan/Library/Android/sdk`):
|
||||
|
||||
- `gradle :app:testDebugUnitTest :app:assembleDebug` → `BUILD SUCCESSFUL`; the
|
||||
JUnit XML totals **267 tests, 0 failures, 0 errors, 0 skipped** (new
|
||||
`ChatApprovalTest`: a pushed frame yields a pending card with the request's
|
||||
action/resources/risk and its three actions, answering once/always/reject settles
|
||||
the card in place, a server-resolved frame offers no actions, a failed reply
|
||||
reopens the request, and the missing-summary fallback; new
|
||||
`ChatProtocolTest.chatPermissionFrameCarriesTheServerResolution`; the reply
|
||||
builder is asserted for `once`, `always` and `reject` through one shared
|
||||
encode/decode round trip, so no decision is asserted more weakly than another).
|
||||
- The rebuilt debug APK was driven on `emulator-5556` against
|
||||
`.approval_check/chat_stub_approval.py` (a stdlib `/connect` WebSocket double
|
||||
that pushes a pending `chat_permission` after a prompt and a server-resolved one
|
||||
for a second session; test scaffolding, not the app). Fresh captures this pass,
|
||||
validated with `android/scripts/capture_png.sh -s emulator-5556` into
|
||||
`~/.local/share/pipelines/data/artifacts/147/3/`:
|
||||
`01_approval_pending.png` (the `Approve edit` card with `src/layout.kt`, the
|
||||
amber `RISK REVIEW` panel and the three actions, the top-bar pan-tool and the
|
||||
chat-chip marker) and `02_approval_answered.png` (the same card settled to
|
||||
`Always allowed`, no actions, the amber risk panel retired). The stub log
|
||||
recorded the `chat_reply` with `decision=always request=req_pending_1`. The
|
||||
already-resolved path was reached too — the `Already resolved` session rendered
|
||||
`Rejected` with the server's note and no controls — but `emulator-5556` shut
|
||||
down before that frame could be captured, and it is not restarted here, so its
|
||||
evidence is the `uiautomator` dump (`uiautomator_server_resolved.xml`) rather
|
||||
than a second screenshot.
|
||||
- **APK publish.** `app-debug.apk` (18,109,180 bytes, sha256
|
||||
`5f58ac6e92a7fbeb2fd023b5604fd7876e9d2546cc7cadf3d871aa7a4b7cce43`) copied to
|
||||
`~/.local/share/pipelines/data/artifacts/147/3/pipelines-debug-wip-305714c.apk`
|
||||
(`305714c` = `git rev-parse --short HEAD`); the running artifacts server serves
|
||||
`curl -I http://10.0.0.75:8080/artifacts/147/3/pipelines-debug-wip-305714c.apk`
|
||||
as `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
|
||||
`Content-Length: 18109180`, and a streamed `GET | shasum -a 256` matched.
|
||||
|
||||
Not verified in this pass: the live brokered server (separate lane), streaming
|
||||
against real OpenCode, and attachments — unchanged from the passes above. The
|
||||
`resolved`/`decision` frame fields are the additive contract the server must send
|
||||
when it reports an already-settled request; the live server does not emit them
|
||||
yet, so only the unit test and the stub exercise that path. `:app:lintDebug` still
|
||||
cannot run here (the Gradle JVM's version string is rejected by AGP 8.7.2 lint),
|
||||
unchanged from the slices above. `emulator-5556` — this lane's standing device,
|
||||
already running when the pass began and never started or restarted here — shut
|
||||
down after the second capture, so the resolved frame was confirmed from the
|
||||
accessibility tree rather than a screenshot. The run's device note (all device work
|
||||
through the attached Pixel, no emulator) conflicts with the task constraint
|
||||
(emulator only, never install on the person's device); this pass resolved it by
|
||||
using the already-running emulator and never installing on the Pixel.
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
android:exported="true"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/Theme.Pipelines"
|
||||
android:windowSoftInputMode="adjustNothing">
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
|
||||
@@ -2,8 +2,15 @@ package net.awan.pipelines.data
|
||||
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import net.awan.pipelines.data.protocol.ChatCreateRequest
|
||||
import net.awan.pipelines.data.protocol.ChatMessage
|
||||
import net.awan.pipelines.data.protocol.ChatPromptRequest
|
||||
import net.awan.pipelines.data.protocol.ChatProtocol
|
||||
import net.awan.pipelines.data.protocol.ChatQuery
|
||||
import net.awan.pipelines.data.protocol.ChatSession
|
||||
import net.awan.pipelines.data.protocol.Message
|
||||
import net.awan.pipelines.data.protocol.PipelineDetail
|
||||
import net.awan.pipelines.data.protocol.PipelineSummary
|
||||
@@ -32,6 +39,9 @@ class PipelinesRepository(
|
||||
) {
|
||||
val connectionState = client.state
|
||||
|
||||
/** Server-pushed chat frames (chat_event / chat_permission), with no request id. */
|
||||
val events: SharedFlow<Message> = client.events
|
||||
|
||||
/** Opens the single shared connection to a validated server URL. */
|
||||
fun connect(validated: ServerUrl.Validated) = client.connect(validated)
|
||||
|
||||
@@ -129,6 +139,62 @@ class PipelinesRepository(
|
||||
Message(type = Protocol.RETRY_RUN, runId = id, requestKey = requestKey),
|
||||
).runDetail ?: throw ProtocolException("The server returned no run detail.")
|
||||
|
||||
// ---- Brokered OpenCode chat (route B): the phone never speaks OpenCode
|
||||
// directly and never holds its credentials. ----
|
||||
|
||||
/** Lists the sessions this server owns, with the `busy` flag the phone renders read-only. */
|
||||
suspend fun chatSessions(): List<ChatSession> =
|
||||
client.call(Message(type = Protocol.CHAT_SESSIONS)).chatSessions ?: emptyList()
|
||||
|
||||
/**
|
||||
* Creates a session and returns it. The server currently answers this type
|
||||
* with an explicit error when it does not broker creation; the caller
|
||||
* surfaces that message rather than guessing at a session id.
|
||||
*/
|
||||
suspend fun chatCreate(title: String, directory: String): ChatSession {
|
||||
val response = client.call(
|
||||
Message(
|
||||
type = Protocol.CHAT_CREATE,
|
||||
chatCreate = ChatCreateRequest(title = title, directory = directory),
|
||||
),
|
||||
)
|
||||
return response.chatSession
|
||||
?: throw ProtocolException("The server did not return the new chat session.")
|
||||
}
|
||||
|
||||
/** Loads a session's stored turns; the server prefers its retained live state. */
|
||||
suspend fun chatMessages(sessionId: String, limit: Int = 0): List<ChatMessage> {
|
||||
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
|
||||
return client.call(
|
||||
Message(type = Protocol.CHAT_MESSAGES, chatQuery = ChatQuery(sessionId = sessionId, limit = limit)),
|
||||
).chatMessages ?: emptyList()
|
||||
}
|
||||
|
||||
/** Sends one prompt; the server echoes an ack and then pushes chat_event frames. */
|
||||
suspend fun chatPrompt(sessionId: String, text: String) {
|
||||
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
|
||||
val trimmed = text.trim()
|
||||
if (trimmed.isEmpty()) throw ProtocolException("Enter a message before sending.")
|
||||
client.call(
|
||||
Message(
|
||||
type = Protocol.CHAT_PROMPT,
|
||||
chatPrompt = ChatPromptRequest(sessionId = sessionId, text = trimmed),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun chatInterrupt(sessionId: String) {
|
||||
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
|
||||
client.call(ChatProtocol.interruptRequest(sessionId))
|
||||
}
|
||||
|
||||
suspend fun chatReply(sessionId: String, requestId: String, decision: String, message: String = "") {
|
||||
if (sessionId.isBlank() || requestId.isBlank()) {
|
||||
throw ProtocolException("A pending permission request is required.")
|
||||
}
|
||||
client.call(ChatProtocol.replyRequest(sessionId, requestId, decision, message))
|
||||
}
|
||||
|
||||
private fun requireConfigured() {
|
||||
if (settings.serverUrl.value.isBlank()) {
|
||||
throw NotConnectedException("Set the Pipelines server URL in Settings first.")
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
package net.awan.pipelines.data.protocol
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
|
||||
/**
|
||||
* Brokered OpenCode chat wire types (route B in the research report): the phone
|
||||
* talks only to `/connect` and the server holds the OpenCode credentials,
|
||||
* translating each type below. The field names and JSON tags mirror
|
||||
* `internal/protocol/chat.go` exactly so the two cannot drift.
|
||||
*
|
||||
* Every list/field is optional with a default, so an older peer or a partial
|
||||
* envelope never crashes the client.
|
||||
*/
|
||||
@Serializable
|
||||
data class ChatSession(
|
||||
val id: String = "",
|
||||
val title: String = "",
|
||||
val agent: String = "",
|
||||
val model: String = "",
|
||||
val directory: String = "",
|
||||
@SerialName("parent_id") val parentId: String = "",
|
||||
@SerialName("created_at") val createdAt: Long = 0,
|
||||
@SerialName("updated_at") val updatedAt: Long = 0,
|
||||
// Another client holds the session, or the server itself owns it as an active
|
||||
// run: the phone shows it read-only instead of letting two clients write the
|
||||
// same conversation.
|
||||
val busy: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ChatCreateRequest(
|
||||
val title: String = "",
|
||||
val directory: String = "",
|
||||
)
|
||||
|
||||
/** The session-scoped request body for chat_messages and chat_interrupt. */
|
||||
@Serializable
|
||||
data class ChatQuery(
|
||||
@SerialName("session_id") val sessionId: String = "",
|
||||
val limit: Int = 0,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ChatPromptRequest(
|
||||
@SerialName("session_id") val sessionId: String = "",
|
||||
val text: String = "",
|
||||
val model: String = "",
|
||||
val agent: String = "",
|
||||
val files: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
/** One stored turn: a user turn is a single text part, an assistant turn holds text/reasoning/tool parts. */
|
||||
@Serializable
|
||||
data class ChatMessage(
|
||||
val id: String = "",
|
||||
@SerialName("session_id") val sessionId: String = "",
|
||||
val role: String = "",
|
||||
val model: String = "",
|
||||
val agent: String = "",
|
||||
@SerialName("created_at") val createdAt: Long = 0,
|
||||
val parts: List<ChatPart> = emptyList(),
|
||||
)
|
||||
|
||||
/** One element of a [ChatMessage]; [type] selects which fields are meaningful. */
|
||||
@Serializable
|
||||
data class ChatPart(
|
||||
val type: String = "",
|
||||
val id: String = "",
|
||||
val text: String = "",
|
||||
val name: String = "",
|
||||
val executed: Boolean = false,
|
||||
val state: ChatToolState? = null,
|
||||
val time: ChatTime? = null,
|
||||
)
|
||||
|
||||
/** The lifecycle of a tool call; [input] is a partial-JSON string while streaming, an object afterwards. */
|
||||
@Serializable
|
||||
data class ChatToolState(
|
||||
val status: String = "",
|
||||
val input: JsonElement? = null,
|
||||
val content: List<ChatToolContent> = emptyList(),
|
||||
val metadata: JsonObject? = null,
|
||||
val error: ChatError? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ChatToolContent(
|
||||
val type: String = "",
|
||||
val text: String = "",
|
||||
val uri: String = "",
|
||||
val mime: String = "",
|
||||
val name: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ChatError(
|
||||
val type: String = "",
|
||||
val message: String = "",
|
||||
)
|
||||
|
||||
/** Epoch-millisecond timing envelope of a tool call. */
|
||||
@Serializable
|
||||
data class ChatTime(
|
||||
val created: Long = 0,
|
||||
val ran: Long = 0,
|
||||
val completed: Long = 0,
|
||||
)
|
||||
|
||||
/**
|
||||
* A server-pushed chat_event frame. [kind] selects the payload: text/reasoning
|
||||
* carry an incremental [delta] for the target [part], tool carries a full [part],
|
||||
* step marks turn progress and usage reports the turn totals.
|
||||
*/
|
||||
@Serializable
|
||||
data class ChatEventFrame(
|
||||
@SerialName("session_id") val sessionId: String = "",
|
||||
@SerialName("message_id") val messageId: String = "",
|
||||
val kind: String = "",
|
||||
val delta: String = "",
|
||||
val part: ChatPart? = null,
|
||||
val step: ChatStep? = null,
|
||||
val usage: ChatUsage? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ChatStep(
|
||||
val status: String = "",
|
||||
val index: Int = 0,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ChatUsage(
|
||||
@SerialName("input_tokens") val inputTokens: Int = 0,
|
||||
@SerialName("output_tokens") val outputTokens: Int = 0,
|
||||
val cost: Double = 0.0,
|
||||
)
|
||||
|
||||
/**
|
||||
* One pending OpenCode approval request the phone answers with chat_reply.
|
||||
*
|
||||
* [resolved] and [decision] carry the server's outcome when it reports a request
|
||||
* that is no longer open (another client answered it, or it expired): the phone
|
||||
* then shows the verdict instead of live controls. They are additive and
|
||||
* optional, so an older peer simply never sets them and every request stays
|
||||
* pending.
|
||||
*/
|
||||
@Serializable
|
||||
data class ChatPermissionFrame(
|
||||
@SerialName("session_id") val sessionId: String = "",
|
||||
@SerialName("request_id") val requestId: String = "",
|
||||
val action: String = "",
|
||||
val resources: List<String> = emptyList(),
|
||||
val save: List<String> = emptyList(),
|
||||
val metadata: JsonObject? = null,
|
||||
val source: ChatPermissionSource? = null,
|
||||
val message: String = "",
|
||||
val resolved: Boolean = false,
|
||||
val decision: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ChatPermissionSource(
|
||||
val type: String = "",
|
||||
@SerialName("message_id") val messageId: String = "",
|
||||
val id: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ChatReplyRequest(
|
||||
@SerialName("session_id") val sessionId: String = "",
|
||||
@SerialName("request_id") val requestId: String = "",
|
||||
val decision: String = "",
|
||||
val message: String = "",
|
||||
)
|
||||
|
||||
/** Chat part/kind/state/reply constants, mirroring `internal/protocol/chat.go`. */
|
||||
object ChatProtocol {
|
||||
const val PART_TEXT = "text"
|
||||
const val PART_REASONING = "reasoning"
|
||||
const val PART_TOOL = "tool"
|
||||
|
||||
const val EVENT_STEP = "step"
|
||||
const val EVENT_USAGE = "usage"
|
||||
|
||||
const val STEP_STARTED = "started"
|
||||
const val STEP_ENDED = "ended"
|
||||
|
||||
const val TOOL_STREAMING = "streaming"
|
||||
const val TOOL_RUNNING = "running"
|
||||
const val TOOL_COMPLETED = "completed"
|
||||
const val TOOL_ERROR = "error"
|
||||
|
||||
const val ROLE_USER = "user"
|
||||
const val ROLE_ASSISTANT = "assistant"
|
||||
|
||||
const val DECISION_ONCE = "once"
|
||||
const val DECISION_ALWAYS = "always"
|
||||
const val DECISION_REJECT = "reject"
|
||||
|
||||
/** A tool call still in flight (no result or error yet). */
|
||||
fun toolRunning(state: ChatToolState?): Boolean = when (state?.status) {
|
||||
TOOL_STREAMING, TOOL_RUNNING -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
/**
|
||||
* The `chat_interrupt` frame the composer's stop control sends: the server
|
||||
* aborts the in-flight turn for [sessionId]. Built here (not inline in the
|
||||
* repository) so production and its unit test share the one wire shape.
|
||||
*/
|
||||
fun interruptRequest(sessionId: String): Message =
|
||||
Message(type = Protocol.CHAT_INTERRUPT, chatQuery = ChatQuery(sessionId = sessionId))
|
||||
|
||||
/**
|
||||
* The `chat_reply` frame that answers one permission request: [decision] is
|
||||
* one of [DECISION_ONCE]/[DECISION_ALWAYS]/[DECISION_REJECT]. Built here (not
|
||||
* inline in the repository) so the approval card's actions and their unit
|
||||
* test share the one wire shape.
|
||||
*/
|
||||
fun replyRequest(sessionId: String, requestId: String, decision: String, message: String = ""): Message =
|
||||
Message(
|
||||
type = Protocol.CHAT_REPLY,
|
||||
chatReply = ChatReplyRequest(
|
||||
sessionId = sessionId,
|
||||
requestId = requestId,
|
||||
decision = decision,
|
||||
message = message,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -53,6 +53,16 @@ object Protocol {
|
||||
const val SEARCH_KIND_STEP = "step"
|
||||
const val SEARCH_KIND_FIELD = "field"
|
||||
const val SEARCH_KIND_ARTIFACT = "artifact"
|
||||
// chat.go (brokered OpenCode chat)
|
||||
const val CHAT_SESSIONS = "chat_sessions"
|
||||
const val CHAT_CREATE = "chat_create"
|
||||
const val CHAT_PROMPT = "chat_prompt"
|
||||
const val CHAT_MESSAGES = "chat_messages"
|
||||
const val CHAT_INTERRUPT = "chat_interrupt"
|
||||
const val CHAT_REPLY = "chat_reply"
|
||||
// Server-pushed frames with no matching request.
|
||||
const val CHAT_EVENT = "chat_event"
|
||||
const val CHAT_PERMISSION = "chat_permission"
|
||||
|
||||
// terminals.go
|
||||
const val SUCCESS_END = "#success"
|
||||
@@ -562,4 +572,15 @@ data class Message(
|
||||
@SerialName("write_paths") val writePaths: List<String>? = null,
|
||||
@SerialName("request_key") val requestKey: String? = null,
|
||||
val workspace: String? = null,
|
||||
// Brokered chat traffic (see Chat.kt). Optional so an older server never
|
||||
// breaks the existing envelope.
|
||||
@SerialName("chat_sessions") val chatSessions: List<ChatSession>? = null,
|
||||
@SerialName("chat_session") val chatSession: ChatSession? = null,
|
||||
@SerialName("chat_create") val chatCreate: ChatCreateRequest? = null,
|
||||
@SerialName("chat_query") val chatQuery: ChatQuery? = null,
|
||||
@SerialName("chat_prompt") val chatPrompt: ChatPromptRequest? = null,
|
||||
@SerialName("chat_messages") val chatMessages: List<ChatMessage>? = null,
|
||||
@SerialName("chat_event") val chatEvent: ChatEventFrame? = null,
|
||||
@SerialName("chat_permission") val chatPermission: ChatPermissionFrame? = null,
|
||||
@SerialName("chat_reply") val chatReply: ChatReplyRequest? = null,
|
||||
)
|
||||
|
||||
@@ -10,8 +10,11 @@ import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
@@ -53,6 +56,15 @@ class PipelinesClient(
|
||||
private val _state = MutableStateFlow<ConnectionState>(ConnectionState.Idle)
|
||||
val state: StateFlow<ConnectionState> = _state.asStateFlow()
|
||||
|
||||
// Unsolicited server frames (server-pushed chat_event / chat_permission /
|
||||
// stream errors). Buffered and dropped-oldest so a slow collector can never
|
||||
// block the socket read loop; chats re-sync from history after a gap anyway.
|
||||
private val _events = MutableSharedFlow<Message>(
|
||||
extraBufferCapacity = 256,
|
||||
onBufferOverflow = kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST,
|
||||
)
|
||||
val events: SharedFlow<Message> = _events.asSharedFlow()
|
||||
|
||||
private val sendLock = Mutex()
|
||||
private val pending = ConcurrentHashMap<String, CompletableDeferred<Message>>()
|
||||
private val sequence = AtomicLong(0)
|
||||
@@ -190,9 +202,12 @@ class PipelinesClient(
|
||||
val deferred = if (id != null) pending.remove(id) else null
|
||||
if (deferred != null) {
|
||||
deferred.complete(message)
|
||||
} else {
|
||||
// Unsolicited envelopes (the connection's initial pipeline_list,
|
||||
// server-pushed chat frames, stream errors) carry no matching id:
|
||||
// hand them to the event stream instead of dropping them.
|
||||
_events.tryEmit(message)
|
||||
}
|
||||
// Unsolicited envelopes (for example the connection's initial
|
||||
// pipeline_list) have no matching id and are intentionally dropped.
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
|
||||
@@ -21,6 +21,7 @@ import net.awan.pipelines.data.PipelinesRepository
|
||||
import net.awan.pipelines.data.RunHistory
|
||||
import net.awan.pipelines.data.SettingsRepository
|
||||
import net.awan.pipelines.data.protocol.BuildInfo
|
||||
import net.awan.pipelines.data.protocol.ChatSession
|
||||
import net.awan.pipelines.data.protocol.PipelineDetail
|
||||
import net.awan.pipelines.data.protocol.PipelineSummary
|
||||
import net.awan.pipelines.data.protocol.Protocol
|
||||
@@ -29,6 +30,8 @@ import net.awan.pipelines.data.protocol.SearchResponse
|
||||
import net.awan.pipelines.data.protocol.SessionEvidence
|
||||
import net.awan.pipelines.data.transport.ConnectionState
|
||||
import net.awan.pipelines.data.transport.ServerUrl
|
||||
import net.awan.pipelines.ui.chat.ChatState
|
||||
import net.awan.pipelines.ui.chat.ChatStore
|
||||
|
||||
/** Generic loading/empty/error/data state used by every screen. */
|
||||
data class LoadState<T>(
|
||||
@@ -110,6 +113,10 @@ class AppViewModel(
|
||||
private val startKeys = ConcurrentHashMap<Long, String>()
|
||||
private val retryKeys = ConcurrentHashMap<Long, String>()
|
||||
|
||||
/** The multi-chat screen state (sessions, open conversations, drafts, scroll). */
|
||||
private val chatStore = ChatStore()
|
||||
val chat: StateFlow<ChatState> = chatStore.state
|
||||
|
||||
init {
|
||||
// Connect on launch when a server URL is already saved, reusing the shared
|
||||
// client and its bounded backoff (no new client, DI or polling). init runs
|
||||
@@ -120,6 +127,50 @@ class AppViewModel(
|
||||
) {
|
||||
reconnect()
|
||||
}
|
||||
observeChatEvents()
|
||||
observeConnection()
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes server-pushed chat frames into the per-chat state, wherever the
|
||||
* frame's session sits in the open order. Frames for a chat that is not open
|
||||
* create a placeholder in [ChatStore.event] so a running background chat
|
||||
* keeps its stream; the operator sees it re-synced from history on return.
|
||||
*/
|
||||
private fun observeChatEvents() {
|
||||
viewModelScope.launch {
|
||||
repository.events.collect { message ->
|
||||
message.chatEvent?.let { chatStore.event(it) }
|
||||
// Never silently drop an approval request: it is held per chat and
|
||||
// answered with chat_reply from the conversation's approval card.
|
||||
message.chatPermission?.let { chatStore.permission(it) }
|
||||
// An unsolicited server error has no request id to match, so it is
|
||||
// the chat stream failing mid-turn: settle the running chat instead
|
||||
// of leaving its indicator spinning forever.
|
||||
if (message.id == null && message.type == Protocol.ERROR) {
|
||||
chatStore.streamError(message.error?.takeIf { it.isNotBlank() } ?: "The chat stream failed.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-syncs every open chat when the socket (re)connects: the frames sent
|
||||
* during the gap are gone, so the conversation is re-fetched from history
|
||||
* rather than trusted. A running chat is marked settled first and a still-live
|
||||
* stream re-asserts it on its next frame, so a stale `Working…` never sticks.
|
||||
*/
|
||||
private fun observeConnection() {
|
||||
viewModelScope.launch {
|
||||
var connected = false
|
||||
connectionState.collect { state ->
|
||||
val isConnected = state is ConnectionState.Connected
|
||||
if (isConnected && !connected) {
|
||||
chatStore.streamResumed().forEach { loadChatHistory(it) }
|
||||
}
|
||||
connected = isConnected
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun updateServerUrlDraft(value: String) {
|
||||
@@ -357,6 +408,125 @@ class AppViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Brokered chat -------------------------------------------------------
|
||||
|
||||
/** Refreshes the server's session list; never clears open conversations. */
|
||||
fun refreshChatSessions() {
|
||||
viewModelScope.launch {
|
||||
chatStore.sessionsLoading()
|
||||
try {
|
||||
chatStore.sessionsLoaded(repository.chatSessions())
|
||||
} catch (t: Throwable) {
|
||||
if (t is CancellationException) throw t
|
||||
chatStore.sessionsFailed(ErrorMessages.describe(t))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens [session] and makes it active. A brand-new chat always loads its
|
||||
* history; a running one re-syncs from the server so a stale copy is never
|
||||
* shown on return.
|
||||
*/
|
||||
fun openChatSession(session: ChatSession) {
|
||||
val needsHistory = chatStore.open(session)
|
||||
if (needsHistory) loadChatHistory(session.id)
|
||||
}
|
||||
|
||||
/** Switches to an already-open chat, re-syncing it when it is running. */
|
||||
fun activateChat(sessionId: String) {
|
||||
if (chatStore.activate(sessionId)) loadChatHistory(sessionId)
|
||||
}
|
||||
|
||||
/** Shows the session list again while keeping every open conversation. */
|
||||
fun showChatList() = chatStore.showList()
|
||||
|
||||
fun closeChat(sessionId: String) = chatStore.close(sessionId)
|
||||
|
||||
fun updateChatDraft(sessionId: String, text: String) = chatStore.draft(sessionId, text)
|
||||
|
||||
fun saveChatScroll(sessionId: String, index: Int, offset: Int) = chatStore.scroll(sessionId, index, offset)
|
||||
|
||||
/** Creates a session on the server and opens it. Reports the server's own error on failure. */
|
||||
fun newChat() {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val created = repository.chatCreate(title = "New chat", directory = settings.workspace.value)
|
||||
chatStore.sessionsLoaded(chatStore.value.sessions + created)
|
||||
chatStore.open(created)
|
||||
chatStore.history(created.id, emptyList())
|
||||
} catch (t: Throwable) {
|
||||
if (t is CancellationException) throw t
|
||||
chatStore.sessionsFailed(ErrorMessages.describe(t))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun loadChatHistory(sessionId: String) {
|
||||
viewModelScope.launch {
|
||||
chatStore.historyLoading(sessionId)
|
||||
try {
|
||||
chatStore.history(sessionId, repository.chatMessages(sessionId, CHAT_HISTORY_LIMIT))
|
||||
} catch (t: Throwable) {
|
||||
if (t is CancellationException) throw t
|
||||
chatStore.failed(sessionId, ErrorMessages.describe(t))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends the active chat's draft. Read-only chats are never written to. */
|
||||
fun sendChatPrompt(sessionId: String) {
|
||||
val thread = chatStore.value.thread(sessionId) ?: return
|
||||
if (thread.readOnly) return
|
||||
val text = thread.draft.trim()
|
||||
if (text.isEmpty()) return
|
||||
chatStore.appendLocalUserMessage(sessionId, text)
|
||||
chatStore.clearDraft(sessionId)
|
||||
chatStore.running(sessionId, true)
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
repository.chatPrompt(sessionId, text)
|
||||
} catch (t: Throwable) {
|
||||
if (t is CancellationException) throw t
|
||||
chatStore.failed(sessionId, ErrorMessages.describe(t))
|
||||
chatStore.running(sessionId, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers a pending approval. The card settles in place optimistically so a
|
||||
* laggy round-trip over a tunnel never shows the old buttons again; a failed
|
||||
* reply reopens the same request and reports why, so the operator can retry
|
||||
* instead of trusting a decision the server never received.
|
||||
*/
|
||||
fun replyChatPermission(sessionId: String, requestId: String, decision: String) {
|
||||
if (sessionId.isBlank() || requestId.isBlank()) return
|
||||
chatStore.answerPermission(sessionId, requestId, decision)
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
repository.chatReply(sessionId, requestId, decision)
|
||||
} catch (t: Throwable) {
|
||||
if (t is CancellationException) throw t
|
||||
chatStore.permissionReplyFailed(sessionId, requestId)
|
||||
chatStore.failed(sessionId, ErrorMessages.describe(t))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stopChat(sessionId: String) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
repository.chatInterrupt(sessionId)
|
||||
} catch (t: Throwable) {
|
||||
if (t is CancellationException) throw t
|
||||
chatStore.failed(sessionId, ErrorMessages.describe(t))
|
||||
} finally {
|
||||
chatStore.running(sessionId, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun <T> load(target: MutableStateFlow<LoadState<T>>, block: suspend () -> T) {
|
||||
viewModelScope.launch {
|
||||
target.value = target.value.copy(loading = true, error = null)
|
||||
@@ -374,6 +544,8 @@ class AppViewModel(
|
||||
|
||||
/** How long the field waits after the last keystroke before issuing one request. */
|
||||
const val SEARCH_DEBOUNCE_MILLIS = 250L
|
||||
/** Bounds one history fetch; the server applies its own cap too. */
|
||||
private const val CHAT_HISTORY_LIMIT = 200
|
||||
|
||||
fun factory(app: PipelinesApplication) = viewModelFactory {
|
||||
initializer { AppViewModel(app.repository, app.settings) }
|
||||
|
||||
@@ -37,6 +37,7 @@ import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Chat
|
||||
import androidx.compose.material.icons.filled.AccountTree
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.History
|
||||
@@ -96,12 +97,14 @@ import net.awan.pipelines.ui.theme.DESTINATION_PILL_RESERVE
|
||||
import net.awan.pipelines.ui.theme.SPACING_M
|
||||
import net.awan.pipelines.ui.theme.SPACING_S
|
||||
import net.awan.pipelines.ui.theme.SPACING_XS
|
||||
import net.awan.pipelines.ui.chat.ChatScreen
|
||||
|
||||
private data class TopDestination(val route: String, val label: String, val icon: ImageVector)
|
||||
|
||||
private val destinations = listOf(
|
||||
TopDestination("pipelines", "Pipelines", Icons.Default.AccountTree),
|
||||
TopDestination("runs", "Runs", Icons.Default.History),
|
||||
TopDestination("chat", "Chat", Icons.AutoMirrored.Filled.Chat),
|
||||
TopDestination("settings", "Settings", Icons.Default.Settings),
|
||||
)
|
||||
|
||||
@@ -263,6 +266,9 @@ fun PipelinesApp(vm: AppViewModel) {
|
||||
listState = runListState,
|
||||
)
|
||||
}
|
||||
composable("chat") {
|
||||
ChatScreen(vm = vm, wide = wide)
|
||||
}
|
||||
composable("settings") {
|
||||
SettingsScreen(vm)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import net.awan.pipelines.data.protocol.ChatPart
|
||||
import net.awan.pipelines.data.protocol.ChatPermissionFrame
|
||||
import net.awan.pipelines.data.protocol.ChatProtocol
|
||||
import net.awan.pipelines.data.protocol.ChatSession
|
||||
import net.awan.pipelines.data.protocol.ChatToolState
|
||||
|
||||
/**
|
||||
* Pure chat formatting helpers shared by the session list and the conversation,
|
||||
* so the same value is never spelled differently in two places. Kept free of
|
||||
* Compose and of the transport so they are unit-testable.
|
||||
*/
|
||||
private val PRETTY_JSON = Json { prettyPrint = true; isLenient = true }
|
||||
|
||||
/**
|
||||
* The INPUT section of a tool call: pretty-printed JSON once the arguments are
|
||||
* an object/array, a partial-JSON string while still streaming, or the raw text
|
||||
* when it cannot be parsed. Blank when there is nothing.
|
||||
*/
|
||||
internal fun prettyToolInput(input: JsonElement?): String = when (input) {
|
||||
null -> ""
|
||||
is JsonObject, is JsonArray -> PRETTY_JSON.encodeToString(JsonElement.serializer(), input)
|
||||
is JsonPrimitive -> input.content
|
||||
else -> input.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* The OUTPUT section of a tool call: the concatenated textual content, or the
|
||||
* literal `(no output)` when the call returned nothing (mirroring jarvis), and
|
||||
* an empty string while the call is still running.
|
||||
*/
|
||||
internal fun toolOutputText(state: ChatToolState?): String {
|
||||
if (state == null) return ""
|
||||
val text = state.content
|
||||
.filter { it.type == "text" && it.text.isNotBlank() }
|
||||
.joinToString("\n") { it.text }
|
||||
if (text.isNotBlank()) return text
|
||||
if (ChatProtocol.toolRunning(state)) return ""
|
||||
return "(no output)"
|
||||
}
|
||||
|
||||
/**
|
||||
* The ERROR section of a failed tool call. The server's error message takes
|
||||
* precedence over any partial output the call had already produced — a failed
|
||||
* call can carry both, and the output text must not be labelled as the error —
|
||||
* falling back to the output text so the block is never blank when the failure
|
||||
* carries no message.
|
||||
*/
|
||||
internal fun toolErrorText(state: ChatToolState?): String {
|
||||
val message = state?.error?.message
|
||||
return if (!message.isNullOrBlank()) message else toolOutputText(state)
|
||||
}
|
||||
|
||||
/** Wall-clock duration of a tool call, or null while it has no completion time. */
|
||||
internal fun toolDurationMillis(part: ChatPart): Long? {
|
||||
val time = part.time ?: return null
|
||||
val start = if (time.ran > 0) time.ran else time.created
|
||||
if (start <= 0 || time.completed <= 0 || time.completed < start) return null
|
||||
return time.completed - start
|
||||
}
|
||||
|
||||
/** True when a tool call ended in an error state. */
|
||||
internal fun toolFailed(state: ChatToolState?): Boolean = state?.status == ChatProtocol.TOOL_ERROR
|
||||
|
||||
/** Compact millisecond duration, e.g. `340ms` / `1.2s` / `2m 3s`. */
|
||||
internal fun formatToolDuration(millis: Long): String = when {
|
||||
millis < 1_000 -> "${millis}ms"
|
||||
millis < 60_000 -> String.format(java.util.Locale.US, "%.1fs", millis / 1000.0)
|
||||
else -> "${millis / 60_000}m ${(millis % 60_000) / 1000}s"
|
||||
}
|
||||
|
||||
/** The chip label for a tool call: its name, or a placeholder when unnamed. */
|
||||
internal fun toolLabel(part: ChatPart): String = part.name.ifBlank { "tool" }
|
||||
|
||||
/**
|
||||
* A session's short title: the server title, or a truncated id when untitled, so
|
||||
* a row never renders as a blank line.
|
||||
*/
|
||||
internal fun sessionTitle(session: ChatSession): String =
|
||||
session.title.ifBlank { session.id.take(18).ifBlank { "Untitled chat" } }
|
||||
|
||||
/**
|
||||
* The status a session row shows. A locally-running turn is reported as
|
||||
* `Running`; otherwise the server's `busy` flag is `Busy · read-only` (another
|
||||
* client holds it, so the composer is disabled), else `Idle`.
|
||||
*
|
||||
* This is the same precedence [ChatThread.readOnly] applies: a turn we started is
|
||||
* `Running` and writable, never the read-only the server's own `busy` flag alone
|
||||
* would imply.
|
||||
*/
|
||||
internal fun sessionStatusLabel(session: ChatSession, runningLocally: Boolean): String = when {
|
||||
runningLocally -> "Running"
|
||||
session.busy -> "Busy · read-only"
|
||||
else -> "Idle"
|
||||
}
|
||||
|
||||
/** Which action the composer's single primary control offers for a chat. */
|
||||
enum class ComposerAction { Send, Stop }
|
||||
|
||||
/**
|
||||
* The composer's primary control: while a turn is in flight the send control
|
||||
* becomes the stop control (interrupt), otherwise it sends the draft. One
|
||||
* derivation drives both the trailing button and the keyboard's send action, so
|
||||
* a running turn can never be sent to from the other control.
|
||||
*/
|
||||
internal fun composerAction(thread: ChatThread): ComposerAction =
|
||||
if (thread.running) ComposerAction.Stop else ComposerAction.Send
|
||||
|
||||
/**
|
||||
* One line of a derived unified diff. [CONTEXT] lines are unchanged, [ADD] came
|
||||
* from the edit's `newString` and [REMOVE] from its `oldString`.
|
||||
*/
|
||||
enum class DiffKind { CONTEXT, ADD, REMOVE }
|
||||
|
||||
data class DiffLine(val kind: DiffKind, val text: String)
|
||||
|
||||
/**
|
||||
* A synthesised edit diff: the file, the true `+N -M` counts and the ordered
|
||||
* lines. [omitted] is how many diff lines are not in [lines] because the edit was
|
||||
* too large to render in full (0 when the whole diff is shown); the counts always
|
||||
* describe the whole edit, never just the rendered prefix.
|
||||
*/
|
||||
data class ToolDiff(
|
||||
val file: String,
|
||||
val added: Int,
|
||||
val removed: Int,
|
||||
val lines: List<DiffLine>,
|
||||
val omitted: Int = 0,
|
||||
)
|
||||
|
||||
/**
|
||||
* Derives a unified diff for an `edit`-family tool call from its
|
||||
* `oldString`/`newString` arguments. The brokered protocol carries no diff field
|
||||
* (research report §2.5), so the +/- view is synthesised here instead. A diff
|
||||
* longer than [MAX_RENDERED_DIFF_LINES] is summarised — only that many lines are
|
||||
* kept, with [ToolDiff.omitted] carrying the rest — so a very large edit cannot
|
||||
* flood the transcript on a phone. Returns null for any other tool, so non-edit
|
||||
* calls keep the INPUT/OUTPUT panel.
|
||||
*/
|
||||
internal fun toolEditDiff(input: JsonElement?): ToolDiff? {
|
||||
val obj = input as? JsonObject ?: return null
|
||||
val old = obj.stringOrNull("oldString", "old_string") ?: return null
|
||||
val new = obj.stringOrNull("newString", "new_string") ?: return null
|
||||
if (old.isEmpty() && new.isEmpty()) return null
|
||||
val lines = lineDiff(old.split("\n"), new.split("\n"))
|
||||
return ToolDiff(
|
||||
file = obj.stringOrNull("filePath", "file_path", "file").orEmpty(),
|
||||
added = lines.count { it.kind == DiffKind.ADD },
|
||||
removed = lines.count { it.kind == DiffKind.REMOVE },
|
||||
lines = lines.take(MAX_RENDERED_DIFF_LINES),
|
||||
omitted = (lines.size - MAX_RENDERED_DIFF_LINES).coerceAtLeast(0),
|
||||
)
|
||||
}
|
||||
|
||||
private fun JsonObject.stringOrNull(vararg keys: String): String? {
|
||||
for (key in keys) {
|
||||
val value = this[key]
|
||||
if (value is JsonPrimitive && value.isString) return value.content
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* A minimal line diff (LCS) so only the changed lines are marked, not the whole
|
||||
* block. A pathologically large edit falls back to a plain remove-then-add block
|
||||
* to bound the quadratic table.
|
||||
*/
|
||||
private fun lineDiff(old: List<String>, new: List<String>): List<DiffLine> {
|
||||
if (old.size > MAX_DIFF_LINES || new.size > MAX_DIFF_LINES) {
|
||||
return old.map { DiffLine(DiffKind.REMOVE, it) } + new.map { DiffLine(DiffKind.ADD, it) }
|
||||
}
|
||||
val m = old.size
|
||||
val n = new.size
|
||||
val lcs = Array(m + 1) { IntArray(n + 1) }
|
||||
for (i in m - 1 downTo 0) {
|
||||
for (j in n - 1 downTo 0) {
|
||||
lcs[i][j] = if (old[i] == new[j]) lcs[i + 1][j + 1] + 1
|
||||
else maxOf(lcs[i + 1][j], lcs[i][j + 1])
|
||||
}
|
||||
}
|
||||
val result = ArrayList<DiffLine>(m + n)
|
||||
var i = 0
|
||||
var j = 0
|
||||
while (i < m && j < n) {
|
||||
when {
|
||||
old[i] == new[j] -> {
|
||||
result.add(DiffLine(DiffKind.CONTEXT, old[i])); i++; j++
|
||||
}
|
||||
lcs[i + 1][j] >= lcs[i][j + 1] -> {
|
||||
result.add(DiffLine(DiffKind.REMOVE, old[i])); i++
|
||||
}
|
||||
else -> {
|
||||
result.add(DiffLine(DiffKind.ADD, new[j])); j++
|
||||
}
|
||||
}
|
||||
}
|
||||
while (i < m) { result.add(DiffLine(DiffKind.REMOVE, old[i])); i++ }
|
||||
while (j < n) { result.add(DiffLine(DiffKind.ADD, new[j])); j++ }
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* How many diff lines are rendered before the remainder is summarised. Small
|
||||
* enough to stay readable on a phone, large enough that ordinary edits are
|
||||
* always shown in full. [MAX_DIFF_LINES] is the larger algorithm guard that
|
||||
* bounds the quadratic LCS table.
|
||||
*/
|
||||
internal const val MAX_RENDERED_DIFF_LINES = 200
|
||||
|
||||
private const val MAX_DIFF_LINES = 400
|
||||
|
||||
/**
|
||||
* How one permission request stands: still waiting for the operator, answered
|
||||
* here (optimistically, while the reply is in flight), or already settled by the
|
||||
* server (another client answered it, or it expired).
|
||||
*/
|
||||
enum class ApprovalState { PENDING, ANSWERED, RESOLVED }
|
||||
|
||||
/**
|
||||
* What the conversation renders for one permission request. Derived purely from
|
||||
* the server's [ChatPermissionFrame] plus the operator's local answer, so the
|
||||
* approval card and its unit test share one model instead of each reading the
|
||||
* frame. [actionable] is true only while nothing has settled the request, which
|
||||
* is what keeps a resolved request from offering stale once/always/reject
|
||||
* controls.
|
||||
*/
|
||||
data class ApprovalCard(
|
||||
val requestId: String,
|
||||
val action: String,
|
||||
val resources: List<String>,
|
||||
val risk: String,
|
||||
val state: ApprovalState,
|
||||
val decision: String = "",
|
||||
val note: String = "",
|
||||
) {
|
||||
/** The once/always/reject controls are live only while the request is open. */
|
||||
val actionable: Boolean get() = state == ApprovalState.PENDING
|
||||
|
||||
/**
|
||||
* The amber risk box is shown while the request is open and after the
|
||||
* operator denies it (jarvis shows it while "pending/denied"), but not for a
|
||||
* request the server already settled, whose note carries the outcome.
|
||||
*/
|
||||
val showRisk: Boolean
|
||||
get() = state == ApprovalState.PENDING ||
|
||||
(state == ApprovalState.ANSWERED && decision == ChatProtocol.DECISION_REJECT)
|
||||
|
||||
/** The card headline: what is being requested, or the verdict once settled. */
|
||||
val headline: String
|
||||
get() = when (state) {
|
||||
ApprovalState.PENDING -> "Approve " + action.ifBlank { "tool call" }
|
||||
ApprovalState.ANSWERED -> decisionLabel(decision)
|
||||
ApprovalState.RESOLVED -> if (decision.isBlank()) "Already resolved" else decisionLabel(decision)
|
||||
}
|
||||
|
||||
/** The one-line explanation under the headline. */
|
||||
val statusLine: String
|
||||
get() = when (state) {
|
||||
ApprovalState.PENDING -> "Waiting for your response"
|
||||
ApprovalState.ANSWERED -> "Waiting for the agent to continue…"
|
||||
ApprovalState.RESOLVED -> note.ifBlank { "Another client already answered this request." }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The approval card for [permission], or null when there is no request to show.
|
||||
* A request the server reports as settled wins over any local answer, so a stale
|
||||
* tap can never reopen controls for a request that is already done.
|
||||
*/
|
||||
internal fun approvalCard(permission: ChatPermissionFrame?, answer: String): ApprovalCard? {
|
||||
if (permission == null || permission.requestId.isBlank()) return null
|
||||
val resolvedByServer = permission.resolved || permission.decision.isNotBlank()
|
||||
val state = when {
|
||||
resolvedByServer -> ApprovalState.RESOLVED
|
||||
answer.isNotBlank() -> ApprovalState.ANSWERED
|
||||
else -> ApprovalState.PENDING
|
||||
}
|
||||
return ApprovalCard(
|
||||
requestId = permission.requestId,
|
||||
action = permission.action,
|
||||
resources = permission.resources.filter { it.isNotBlank() },
|
||||
risk = permissionRiskText(permission),
|
||||
state = state,
|
||||
decision = if (resolvedByServer) permission.decision else answer,
|
||||
note = if (resolvedByServer) permission.message else "",
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The text in the amber risk-review box: the server's own summary when it carries
|
||||
* one (jarvis shows the model's risk summary), otherwise a neutral sentence
|
||||
* naming the action so the box is never blank.
|
||||
*/
|
||||
internal fun permissionRiskText(permission: ChatPermissionFrame): String {
|
||||
if (permission.message.isNotBlank()) return permission.message
|
||||
val what = permission.action.ifBlank { "a tool call" }
|
||||
return "The agent is asking to run $what; review the request before allowing."
|
||||
}
|
||||
|
||||
/** A human label for a once/always/reject decision, blank-safe. */
|
||||
internal fun decisionLabel(decision: String): String = when (decision) {
|
||||
ChatProtocol.DECISION_ONCE -> "Allowed once"
|
||||
ChatProtocol.DECISION_ALWAYS -> "Always allowed"
|
||||
ChatProtocol.DECISION_REJECT -> "Rejected"
|
||||
else -> "Resolved"
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,429 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import net.awan.pipelines.data.protocol.ChatEventFrame
|
||||
import net.awan.pipelines.data.protocol.ChatMessage
|
||||
import net.awan.pipelines.data.protocol.ChatPart
|
||||
import net.awan.pipelines.data.protocol.ChatPermissionFrame
|
||||
import net.awan.pipelines.data.protocol.ChatProtocol
|
||||
import net.awan.pipelines.data.protocol.ChatSession
|
||||
|
||||
/**
|
||||
* A saved scroll position inside one conversation. Kept as Android-free
|
||||
* primitives so it is part of the pure model and can survive a chat switch (the
|
||||
* caller feeds it back into the list's state).
|
||||
*/
|
||||
data class ChatScrollPosition(val index: Int = 0, val offset: Int = 0)
|
||||
|
||||
/**
|
||||
* One open conversation. The conversation itself, whether it is running, its
|
||||
* unsent composer draft and its scroll position all live here, so switching to
|
||||
* another chat and back can never lose any of them.
|
||||
*/
|
||||
data class ChatThread(
|
||||
val sessionId: String,
|
||||
val title: String = "",
|
||||
val directory: String = "",
|
||||
val model: String = "",
|
||||
val agent: String = "",
|
||||
val updatedAt: Long = 0,
|
||||
/** The server reports another client (or an active run) holds this session. */
|
||||
val busy: Boolean = false,
|
||||
val messages: List<ChatMessage> = emptyList(),
|
||||
val loading: Boolean = false,
|
||||
val loaded: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** A turn is in flight for this session; it keeps running when we switch away. */
|
||||
val running: Boolean = false,
|
||||
/**
|
||||
* Wall-clock epoch millis the in-flight turn began, or 0 when it is not
|
||||
* running. Stored on the thread (not in the composable) so the running
|
||||
* indicator's elapsed time survives a chat switch, and cleared the moment
|
||||
* the turn settles.
|
||||
*/
|
||||
val runningSince: Long = 0,
|
||||
/** The unsent composer text for this chat. */
|
||||
val draft: String = "",
|
||||
val scroll: ChatScrollPosition = ChatScrollPosition(),
|
||||
/** The server's pending approval for this session, answered with chat_reply. */
|
||||
val permission: ChatPermissionFrame? = null,
|
||||
/**
|
||||
* The operator's local answer to [permission] (`once`/`always`/`reject`), or
|
||||
* blank while it is still open. Held on the thread so the approval card can
|
||||
* settle in place optimistically and survives a chat switch.
|
||||
*/
|
||||
val permissionAnswer: String = "",
|
||||
) {
|
||||
/**
|
||||
* Read-only while another client holds the session: the composer must never
|
||||
* write to it. A turn we started ourselves keeps the session writable even
|
||||
* though the server reports it busy (the server owns it as our active run),
|
||||
* so the one rule here agrees with [sessionStatusLabel]'s `Running` case.
|
||||
*/
|
||||
val readOnly: Boolean get() = busy && !running
|
||||
|
||||
/** Whether the composer's send action is allowed. */
|
||||
val canSend: Boolean get() = !readOnly && draft.isNotBlank()
|
||||
|
||||
/**
|
||||
* Non-negative elapsed time of an in-flight turn at [nowMillis], or 0 once it
|
||||
* has settled. Pure, so the running indicator and its unit test share the one
|
||||
* derivation instead of each subtracting the start themselves.
|
||||
*/
|
||||
fun elapsedMillis(nowMillis: Long): Long =
|
||||
if (running && runningSince in 1 until nowMillis) nowMillis - runningSince else 0
|
||||
}
|
||||
|
||||
/**
|
||||
* The multi-chat screen state. [sessions] is the server's list; [open] is the
|
||||
* ordered set of conversations the operator has opened, each preserved
|
||||
* independently; [activeId] is the one currently on screen.
|
||||
*/
|
||||
data class ChatState(
|
||||
val sessions: List<ChatSession> = emptyList(),
|
||||
val sessionsLoading: Boolean = false,
|
||||
val sessionsLoaded: Boolean = false,
|
||||
val sessionsError: String? = null,
|
||||
val open: List<ChatThread> = emptyList(),
|
||||
val activeId: String? = null,
|
||||
) {
|
||||
val active: ChatThread? get() = open.firstOrNull { it.sessionId == activeId }
|
||||
|
||||
fun thread(sessionId: String): ChatThread? = open.firstOrNull { it.sessionId == sessionId }
|
||||
}
|
||||
|
||||
/**
|
||||
* The multi-chat state model: a small, Android-free holder of [ChatState] with
|
||||
* the transitions the chat surface needs. Keeping it free of Compose and of the
|
||||
* transport makes the multi-chat guarantees (per-chat draft/scroll/conversation,
|
||||
* running survives a switch and re-syncs on return) unit-testable without a
|
||||
* device or a server.
|
||||
*
|
||||
* Method contracts that matter:
|
||||
* - [open] and [activate] return true when the caller must (re-)fetch history;
|
||||
* a running session must re-sync on return so a stale copy is never shown.
|
||||
* - [event] applies a server frame to its session's thread whether or not that
|
||||
* thread is on screen, so a background chat never loses its stream.
|
||||
*
|
||||
* [now] is injectable so the running indicator's elapsed time is testable without
|
||||
* a device clock.
|
||||
*/
|
||||
class ChatStore(private val now: () -> Long = System::currentTimeMillis) {
|
||||
|
||||
private val _state = MutableStateFlow(ChatState())
|
||||
val state: StateFlow<ChatState> = _state.asStateFlow()
|
||||
|
||||
val value: ChatState get() = _state.value
|
||||
|
||||
// ---- Session list --------------------------------------------------------
|
||||
|
||||
fun sessionsLoading() {
|
||||
_state.value = _state.value.copy(sessionsLoading = true, sessionsError = null)
|
||||
}
|
||||
|
||||
fun sessionsFailed(message: String) {
|
||||
_state.value = _state.value.copy(sessionsLoading = false, sessionsError = message)
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the server's session list and folds its title/busy flags into any
|
||||
* already-open thread, so a status change is reflected without dropping the
|
||||
* conversation. An open thread the server no longer lists is kept (its
|
||||
* conversation is still the operator's).
|
||||
*/
|
||||
fun sessionsLoaded(sessions: List<ChatSession>) {
|
||||
val byId = sessions.associateBy { it.id }
|
||||
val open = _state.value.open.map { thread ->
|
||||
val session = byId[thread.sessionId] ?: return@map thread
|
||||
thread.copy(
|
||||
title = session.title.ifBlank { thread.title },
|
||||
directory = session.directory.ifBlank { thread.directory },
|
||||
busy = session.busy,
|
||||
)
|
||||
}
|
||||
_state.value = _state.value.copy(
|
||||
sessions = sessions,
|
||||
open = open,
|
||||
sessionsLoading = false,
|
||||
sessionsLoaded = true,
|
||||
sessionsError = null,
|
||||
)
|
||||
}
|
||||
|
||||
// ---- Opening / switching -------------------------------------------------
|
||||
|
||||
/**
|
||||
* Opens [session] (idempotently) and makes it active. Returns true when its
|
||||
* history must be fetched: a brand-new thread always, and a re-opened one
|
||||
* whose state may have moved on (it is running, or was never loaded).
|
||||
*/
|
||||
fun open(session: ChatSession): Boolean {
|
||||
val existing = _state.value.thread(session.id)
|
||||
if (existing == null) {
|
||||
val thread = ChatThread(
|
||||
sessionId = session.id,
|
||||
title = session.title,
|
||||
directory = session.directory,
|
||||
model = session.model,
|
||||
agent = session.agent,
|
||||
updatedAt = session.updatedAt,
|
||||
busy = session.busy,
|
||||
)
|
||||
_state.value = _state.value.copy(open = _state.value.open + thread, activeId = session.id)
|
||||
return true
|
||||
}
|
||||
val merged = existing.copy(
|
||||
title = session.title.ifBlank { existing.title },
|
||||
directory = session.directory.ifBlank { existing.directory },
|
||||
busy = session.busy,
|
||||
)
|
||||
_state.value = _state.value.copy(
|
||||
open = _state.value.open.map { if (it.sessionId == session.id) merged else it },
|
||||
activeId = session.id,
|
||||
)
|
||||
return needsResync(merged)
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes an already-open thread active. Returns true when its history must be
|
||||
* re-fetched first: a running session is re-synced from the server on return
|
||||
* so the operator never sees a stale conversation.
|
||||
*/
|
||||
fun activate(sessionId: String): Boolean {
|
||||
val thread = _state.value.thread(sessionId) ?: return false
|
||||
_state.value = _state.value.copy(activeId = sessionId)
|
||||
return needsResync(thread)
|
||||
}
|
||||
|
||||
fun close(sessionId: String) {
|
||||
val open = _state.value.open.filterNot { it.sessionId == sessionId }
|
||||
val active = if (_state.value.activeId == sessionId) open.lastOrNull()?.sessionId else _state.value.activeId
|
||||
_state.value = _state.value.copy(open = open, activeId = active)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns to the session list without closing any conversation: [activeId]
|
||||
* becomes null while [ChatState.open] is untouched, so every open chat keeps
|
||||
* its messages, draft and scroll.
|
||||
*/
|
||||
fun showList() {
|
||||
if (_state.value.activeId != null) {
|
||||
_state.value = _state.value.copy(activeId = null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun needsResync(thread: ChatThread): Boolean = thread.running || !thread.loaded
|
||||
|
||||
// ---- Per-thread edits ----------------------------------------------------
|
||||
|
||||
fun draft(sessionId: String, text: String) = update(sessionId) { it.copy(draft = text) }
|
||||
|
||||
fun clearDraft(sessionId: String) = update(sessionId) { it.copy(draft = "") }
|
||||
|
||||
fun scroll(sessionId: String, index: Int, offset: Int) =
|
||||
update(sessionId) { it.copy(scroll = ChatScrollPosition(index, offset)) }
|
||||
|
||||
fun historyLoading(sessionId: String) = update(sessionId) { it.copy(loading = true, error = null) }
|
||||
|
||||
fun failed(sessionId: String, message: String) =
|
||||
update(sessionId) { it.copy(loading = false, error = message) }
|
||||
|
||||
/**
|
||||
* Replaces a thread's conversation with the server's authoritative history.
|
||||
* The running flag is left as-is: history alone cannot say whether a turn is
|
||||
* still in flight.
|
||||
*/
|
||||
fun history(sessionId: String, messages: List<ChatMessage>) = update(sessionId) {
|
||||
it.copy(messages = messages, loading = false, loaded = true, error = null)
|
||||
}
|
||||
|
||||
fun running(sessionId: String, running: Boolean) = update(sessionId) { setRunning(it, running) }
|
||||
|
||||
/**
|
||||
* The stream resumed (the socket reconnected): every frame that was feeding an
|
||||
* in-flight turn is gone, so no thread keeps claiming to run until a fresh
|
||||
* frame proves otherwise, and the caller re-fetches each open chat's history.
|
||||
* Returning every open id (not only the running ones) means a gap that
|
||||
* silently swallowed the end of a turn is repaired too. Re-fetching replaces
|
||||
* the conversation wholesale, so a resync can neither duplicate nor drop text.
|
||||
*/
|
||||
fun streamResumed(): List<String> {
|
||||
val ids = _state.value.open.map { it.sessionId }
|
||||
if (ids.isEmpty()) return ids
|
||||
_state.value = _state.value.copy(
|
||||
open = _state.value.open.map { if (it.running) it.copy(running = false, runningSince = 0) else it },
|
||||
)
|
||||
return ids
|
||||
}
|
||||
|
||||
/**
|
||||
* A server-pushed stream error carries no session id (the brokered protocol
|
||||
* cannot attribute it), so settle the one turn it can only have come from: the
|
||||
* sole running chat, or the active one when several are in flight. With
|
||||
* nothing running there is no turn to settle and it is ignored; the server's
|
||||
* text is kept so the operator sees why the turn stopped.
|
||||
*/
|
||||
fun streamError(message: String) {
|
||||
val running = _state.value.open.filter { it.running }
|
||||
val target = when {
|
||||
running.isEmpty() -> return
|
||||
running.size == 1 -> running.single()
|
||||
else -> running.firstOrNull { it.sessionId == _state.value.activeId } ?: return
|
||||
}
|
||||
update(target.sessionId) { setRunning(it.copy(error = message), false) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The server pushed an approval request for this session, or reported one it
|
||||
* has already settled. A frame for a *new* request replaces any leftover card
|
||||
* from the previous one; a frame for the same request (for example a resolved
|
||||
* re-push) keeps the local answer and applies the server's outcome.
|
||||
*/
|
||||
fun permission(frame: ChatPermissionFrame) {
|
||||
if (frame.sessionId.isBlank()) return
|
||||
ensureThread(frame.sessionId)
|
||||
update(frame.sessionId) {
|
||||
val sameRequest = it.permission?.requestId == frame.requestId && frame.requestId.isNotBlank()
|
||||
it.copy(
|
||||
permission = frame,
|
||||
permissionAnswer = if (sameRequest) it.permissionAnswer else "",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The operator's decision on the pending request, recorded optimistically so
|
||||
* the card settles in place before the round-trip: the buttons are never left
|
||||
* offering a decision already made. A request that is no longer the one on
|
||||
* screen is ignored.
|
||||
*/
|
||||
fun answerPermission(sessionId: String, requestId: String, decision: String) = update(sessionId) {
|
||||
if (it.permission?.requestId != requestId) it else it.copy(permissionAnswer = decision)
|
||||
}
|
||||
|
||||
/** The reply failed: reopen the same request so the operator can try again. */
|
||||
fun permissionReplyFailed(sessionId: String, requestId: String) = update(sessionId) {
|
||||
if (it.permission?.requestId != requestId) it else it.copy(permissionAnswer = "")
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends the operator's just-sent prompt optimistically, so the bubble is
|
||||
* visible before the ack and history round-trip. History later reconciles it.
|
||||
*/
|
||||
fun appendLocalUserMessage(sessionId: String, text: String) = update(sessionId) {
|
||||
val message = ChatMessage(
|
||||
id = LOCAL_MESSAGE_PREFIX + (it.messages.count { m -> m.id.startsWith(LOCAL_MESSAGE_PREFIX) } + 1),
|
||||
sessionId = sessionId,
|
||||
role = ChatProtocol.ROLE_USER,
|
||||
parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = text)),
|
||||
)
|
||||
it.copy(messages = it.messages + message)
|
||||
}
|
||||
|
||||
// ---- Streaming events ----------------------------------------------------
|
||||
|
||||
/**
|
||||
* Folds one pushed [frame] into its session's thread, creating a placeholder
|
||||
* thread when the frame arrives for a chat that is not open, so a background
|
||||
* chat keeps its stream instead of dropping it.
|
||||
*/
|
||||
fun event(frame: ChatEventFrame) {
|
||||
if (frame.sessionId.isBlank()) return
|
||||
ensureThread(frame.sessionId)
|
||||
when (frame.kind) {
|
||||
ChatProtocol.PART_TEXT, ChatProtocol.PART_REASONING -> applyDelta(frame)
|
||||
ChatProtocol.PART_TOOL -> applyTool(frame)
|
||||
ChatProtocol.EVENT_STEP -> {
|
||||
val started = frame.step?.status != ChatProtocol.STEP_ENDED
|
||||
update(frame.sessionId) { setRunning(it, started) }
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a placeholder thread for a session that is not open, so a frame for
|
||||
* a background chat is kept instead of dropped. A no-op when it already exists.
|
||||
*/
|
||||
private fun ensureThread(sessionId: String) {
|
||||
if (_state.value.thread(sessionId) != null) return
|
||||
val session = _state.value.sessions.firstOrNull { it.id == sessionId }
|
||||
val placeholder = ChatThread(
|
||||
sessionId = sessionId,
|
||||
title = session?.title ?: "",
|
||||
directory = session?.directory ?: "",
|
||||
busy = session?.busy ?: false,
|
||||
)
|
||||
_state.value = _state.value.copy(open = _state.value.open + placeholder)
|
||||
}
|
||||
|
||||
private fun applyDelta(frame: ChatEventFrame) {
|
||||
val partId = frame.part?.id.orEmpty()
|
||||
if (partId.isEmpty() || frame.delta.isEmpty()) return
|
||||
upsertPart(frame, partId) { existing ->
|
||||
existing?.copy(text = existing.text + frame.delta)
|
||||
?: ChatPart(type = frame.kind, id = partId, text = frame.delta)
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyTool(frame: ChatEventFrame) {
|
||||
val part = frame.part ?: return
|
||||
if (part.id.isEmpty()) return
|
||||
upsertPart(frame, part.id) { part }
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds or creates the assistant message [frame] targets and the part [partId]
|
||||
* inside it, replacing it via [upsert] (the old part when it exists, else
|
||||
* null), then marks the thread running. The text/reasoning delta and the tool
|
||||
* upsert share this so the two cannot drift.
|
||||
*/
|
||||
private fun upsertPart(frame: ChatEventFrame, partId: String, upsert: (ChatPart?) -> ChatPart) {
|
||||
update(frame.sessionId) { thread ->
|
||||
val messages = thread.messages.toMutableList()
|
||||
val index = messages.indexOfLast { it.id == frame.messageId }
|
||||
val message = if (index >= 0) {
|
||||
messages[index]
|
||||
} else {
|
||||
ChatMessage(
|
||||
id = frame.messageId,
|
||||
sessionId = frame.sessionId,
|
||||
role = ChatProtocol.ROLE_ASSISTANT,
|
||||
).also { messages.add(it) }
|
||||
}
|
||||
val resolvedIndex = if (index >= 0) index else messages.lastIndex
|
||||
val parts = message.parts.toMutableList()
|
||||
val partIndex = parts.indexOfFirst { it.id == partId }
|
||||
val updated = upsert(if (partIndex >= 0) parts[partIndex] else null)
|
||||
if (partIndex >= 0) parts[partIndex] = updated else parts.add(updated)
|
||||
messages[resolvedIndex] = message.copy(parts = parts)
|
||||
setRunning(thread.copy(messages = messages), true)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a running transition: a turn that begins is stamped with the wall
|
||||
* clock so the indicator can tick, a redundant `true` keeps the original
|
||||
* stamp, and settling clears it. The one place `running` is set, so the two
|
||||
* can never disagree.
|
||||
*/
|
||||
private fun setRunning(thread: ChatThread, running: Boolean): ChatThread = when {
|
||||
running && !thread.running -> thread.copy(running = true, runningSince = now())
|
||||
running -> thread
|
||||
else -> thread.copy(running = false, runningSince = 0)
|
||||
}
|
||||
|
||||
private fun update(sessionId: String, block: (ChatThread) -> ChatThread) {
|
||||
val current = _state.value
|
||||
if (current.open.none { it.sessionId == sessionId }) return
|
||||
_state.value = current.copy(
|
||||
open = current.open.map { if (it.sessionId == sessionId) block(it) else it },
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val LOCAL_MESSAGE_PREFIX = "local-"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.LinkAnnotation
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.TextLinkStyles
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextDecoration
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.text.withLink
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.dp
|
||||
import net.awan.pipelines.ui.components.CodeBlock
|
||||
import net.awan.pipelines.ui.theme.HAIRLINE_DP
|
||||
import net.awan.pipelines.ui.theme.pipelinesText
|
||||
|
||||
/**
|
||||
* A small, dependency-free CommonMark subset for assistant prose. The brokered
|
||||
* protocol carries assistant text as markdown and the reference experience renders
|
||||
* it (research §1.2): body paragraphs, `#`..`######` headings, fenced code (the
|
||||
* shared [CodeBlock], so the copy action comes for free), block quotes, bullet and
|
||||
* ordered lists, `|` tables, thematic rules, and inline code / bold / italic /
|
||||
* links. Anything outside the subset renders as plain text, never dropped.
|
||||
*
|
||||
* The parser is pure Kotlin (no Compose, no transport) so it is unit-testable; the
|
||||
* composables below turn the same blocks into themed, selectable content.
|
||||
*/
|
||||
|
||||
// ---- Parsed model ------------------------------------------------------------
|
||||
|
||||
internal sealed interface MdBlock
|
||||
|
||||
internal data class MdHeading(val level: Int, val text: String) : MdBlock
|
||||
internal data class MdParagraph(val text: String) : MdBlock
|
||||
internal data class MdCodeBlock(val language: String, val code: String) : MdBlock
|
||||
internal data class MdQuote(val lines: List<String>) : MdBlock
|
||||
internal data class MdListBlock(val ordered: Boolean, val items: List<String>) : MdBlock
|
||||
internal data class MdTableBlock(val header: List<String>, val rows: List<List<String>>) : MdBlock
|
||||
internal data object MdRule : MdBlock
|
||||
|
||||
internal sealed interface MdSpan
|
||||
|
||||
internal data class MdPlain(val text: String) : MdSpan
|
||||
internal data class MdCodeSpan(val text: String) : MdSpan
|
||||
internal data class MdStrong(val spans: List<MdSpan>) : MdSpan
|
||||
internal data class MdEmphasis(val spans: List<MdSpan>) : MdSpan
|
||||
internal data class MdLinkSpan(val spans: List<MdSpan>, val url: String) : MdSpan
|
||||
|
||||
// ---- Block parser ------------------------------------------------------------
|
||||
|
||||
/** Parses [source] into the block list the renderer walks. Never throws. */
|
||||
internal fun parseMarkdown(source: String): List<MdBlock> {
|
||||
val lines = source.replace("\r\n", "\n").replace('\r', '\n').split('\n')
|
||||
val blocks = mutableListOf<MdBlock>()
|
||||
var i = 0
|
||||
while (i < lines.size) {
|
||||
val line = lines[i]
|
||||
val trimmed = line.trim()
|
||||
when {
|
||||
trimmed.isEmpty() -> i++
|
||||
|
||||
fenceRun(trimmed) != null -> {
|
||||
val fence = fenceRun(trimmed)!!
|
||||
val language = trimmed.removePrefix(fence).trim().substringBefore(' ')
|
||||
val code = mutableListOf<String>()
|
||||
i++
|
||||
while (i < lines.size && fenceRun(lines[i].trim()) == null) {
|
||||
code.add(lines[i])
|
||||
i++
|
||||
}
|
||||
if (i < lines.size) i++ // consume the closing fence
|
||||
blocks.add(MdCodeBlock(language, code.joinToString("\n")))
|
||||
}
|
||||
|
||||
headingLevel(trimmed) > 0 -> {
|
||||
val level = headingLevel(trimmed)
|
||||
blocks.add(MdHeading(level, trimmed.drop(level).trim().trimEnd('#')))
|
||||
i++
|
||||
}
|
||||
|
||||
isRule(trimmed) -> {
|
||||
blocks.add(MdRule)
|
||||
i++
|
||||
}
|
||||
|
||||
trimmed.startsWith(">") -> {
|
||||
val quote = mutableListOf<String>()
|
||||
while (i < lines.size && lines[i].trim().startsWith(">")) {
|
||||
quote.add(lines[i].trim().removePrefix(">").removePrefix(" ").trimEnd())
|
||||
i++
|
||||
}
|
||||
blocks.add(MdQuote(quote))
|
||||
}
|
||||
|
||||
isTableStart(lines, i) -> {
|
||||
val header = splitRow(lines[i])
|
||||
i += 2 // header + delimiter row
|
||||
val rows = mutableListOf<List<String>>()
|
||||
while (i < lines.size && lines[i].contains('|') && lines[i].isNotBlank()) {
|
||||
rows.add(fitRow(splitRow(lines[i]), header.size))
|
||||
i++
|
||||
}
|
||||
blocks.add(MdTableBlock(header, rows))
|
||||
}
|
||||
|
||||
listMarker(line) != null -> {
|
||||
val ordered = listMarker(line)!!.first
|
||||
val items = mutableListOf<String>()
|
||||
while (i < lines.size && listMarker(lines[i])?.first == ordered) {
|
||||
items.add(listMarker(lines[i])!!.second)
|
||||
i++
|
||||
}
|
||||
blocks.add(MdListBlock(ordered, items))
|
||||
}
|
||||
|
||||
else -> {
|
||||
val paragraph = mutableListOf(line.trim())
|
||||
i++
|
||||
while (i < lines.size && lines[i].isNotBlank() && !startsBlock(lines, i)) {
|
||||
paragraph.add(lines[i].trim())
|
||||
i++
|
||||
}
|
||||
blocks.add(MdParagraph(paragraph.joinToString(" ")))
|
||||
}
|
||||
}
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
/** The fence run (` ``` ` / `~~~`) a line opens or closes with, or null. */
|
||||
private fun fenceRun(trimmed: String): String? {
|
||||
val first = trimmed.firstOrNull() ?: return null
|
||||
if (first != '`' && first != '~') return null
|
||||
val run = trimmed.takeWhile { it == first }
|
||||
return if (run.length >= 3) run else null
|
||||
}
|
||||
|
||||
private fun headingLevel(trimmed: String): Int {
|
||||
val hashes = trimmed.takeWhile { it == '#' }.length
|
||||
if (hashes == 0 || hashes > 6) return 0
|
||||
return if (trimmed.length == hashes || trimmed[hashes] == ' ') hashes else 0
|
||||
}
|
||||
|
||||
private fun isRule(trimmed: String): Boolean =
|
||||
trimmed.length >= 3 && trimmed.all { it == trimmed[0] } && trimmed[0] in "-*_"
|
||||
|
||||
/** True when [lines] at [index] is a table header followed by a `---` delimiter row. */
|
||||
private fun isTableStart(lines: List<String>, index: Int): Boolean {
|
||||
if (index + 1 >= lines.size || !lines[index].contains('|')) return false
|
||||
val delimiter = splitRow(lines[index + 1])
|
||||
if (delimiter.isEmpty() || splitRow(lines[index]).size < 2) return false
|
||||
return delimiter.all { cell -> cell.isNotEmpty() && cell.all { it == '-' || it == ':' } && cell.contains('-') }
|
||||
}
|
||||
|
||||
/** Splits a table row on unescaped `|`, dropping the leading/trailing empty cell. */
|
||||
private fun splitRow(line: String): List<String> =
|
||||
line.trim().removePrefix("|").removeSuffix("|").split('|').map { it.replace("\\|", "|").trim() }
|
||||
|
||||
private fun fitRow(row: List<String>, size: Int): List<String> =
|
||||
List(size) { row.getOrElse(it) { "" } }
|
||||
|
||||
/** The ordered flag and item text of a list line, or null for a non-item line. */
|
||||
private fun listMarker(line: String): Pair<Boolean, String>? {
|
||||
val trimmed = line.trimStart()
|
||||
val orderedMatch = ORDERED_ITEM.matchEntire(trimmed)
|
||||
if (orderedMatch != null) return true to orderedMatch.groupValues[2]
|
||||
val bulletMatch = BULLET_ITEM.matchEntire(trimmed)
|
||||
if (bulletMatch != null) return false to bulletMatch.groupValues[2]
|
||||
return null
|
||||
}
|
||||
|
||||
/** True when [lines] at [index] begins a block that must interrupt a paragraph. */
|
||||
private fun startsBlock(lines: List<String>, index: Int): Boolean {
|
||||
val trimmed = lines[index].trim()
|
||||
return fenceRun(trimmed) != null ||
|
||||
headingLevel(trimmed) > 0 ||
|
||||
isRule(trimmed) ||
|
||||
trimmed.startsWith(">") ||
|
||||
listMarker(lines[index]) != null ||
|
||||
isTableStart(lines, index)
|
||||
}
|
||||
|
||||
// ---- Inline parser -----------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Parses inline markup in [text] into a flat span tree. Handles `` `code` ``,
|
||||
* `**bold**` / `__bold__`, `*italic*` / `_italic_`, `[label](url)` and bare
|
||||
* `http(s)://` autolinks; everything else stays plain text. Underscore emphasis
|
||||
* requires word boundaries so `snake_case` is never italicised.
|
||||
*/
|
||||
internal fun parseInline(text: String): List<MdSpan> {
|
||||
val spans = mutableListOf<MdSpan>()
|
||||
val buffer = StringBuilder()
|
||||
var i = 0
|
||||
|
||||
fun flush() {
|
||||
if (buffer.isNotEmpty()) {
|
||||
spans.add(MdPlain(buffer.toString()))
|
||||
buffer.clear()
|
||||
}
|
||||
}
|
||||
|
||||
while (i < text.length) {
|
||||
val c = text[i]
|
||||
when {
|
||||
c == '`' -> {
|
||||
val end = text.indexOf('`', i + 1)
|
||||
if (end > i) {
|
||||
flush()
|
||||
spans.add(MdCodeSpan(text.substring(i + 1, end)))
|
||||
i = end + 1
|
||||
} else {
|
||||
buffer.append(c); i++
|
||||
}
|
||||
}
|
||||
|
||||
c == '*' || c == '_' -> {
|
||||
val doubled = i + 1 < text.length && text[i + 1] == c
|
||||
val marker = if (doubled) "$c$c" else c.toString()
|
||||
val boundOk = c != '_' || i == 0 || !text[i - 1].isLetterOrDigit()
|
||||
val end = if (boundOk) text.indexOf(marker, i + marker.length) else -1
|
||||
val closes = end > i + marker.length &&
|
||||
(c != '_' || end + 1 >= text.length || !text[end + 1].isLetterOrDigit())
|
||||
if (closes) {
|
||||
flush()
|
||||
val inner = parseInline(text.substring(i + marker.length, end))
|
||||
spans.add(if (doubled) MdStrong(inner) else MdEmphasis(inner))
|
||||
i = end + marker.length
|
||||
} else {
|
||||
buffer.append(c); i++
|
||||
}
|
||||
}
|
||||
|
||||
c == '[' -> {
|
||||
val close = text.indexOf(']', i + 1)
|
||||
if (close > i && close + 1 < text.length && text[close + 1] == '(') {
|
||||
val urlEnd = text.indexOf(')', close + 2)
|
||||
val url = if (urlEnd > close) text.substring(close + 2, urlEnd).trim() else ""
|
||||
if (url.isNotEmpty()) {
|
||||
flush()
|
||||
spans.add(MdLinkSpan(parseInline(text.substring(i + 1, close)), url))
|
||||
i = urlEnd + 1
|
||||
} else {
|
||||
buffer.append(c); i++
|
||||
}
|
||||
} else {
|
||||
buffer.append(c); i++
|
||||
}
|
||||
}
|
||||
|
||||
else -> {
|
||||
val url = autolinkAt(text, i)
|
||||
if (url != null) {
|
||||
flush()
|
||||
spans.add(MdLinkSpan(listOf(MdPlain(url)), url))
|
||||
i += url.length
|
||||
} else {
|
||||
buffer.append(c); i++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
flush()
|
||||
return spans
|
||||
}
|
||||
|
||||
/** A bare `http(s)://` URL starting exactly at [index], trailing punctuation trimmed. */
|
||||
private fun autolinkAt(text: String, index: Int): String? {
|
||||
if (!text.startsWith("http://", index) && !text.startsWith("https://", index)) return null
|
||||
var end = index
|
||||
while (end < text.length && !text[end].isWhitespace() && text[end] !in "<>\"'") end++
|
||||
var url = text.substring(index, end)
|
||||
while (url.isNotEmpty() && url.last() in ".,;:!?)]}") url = url.dropLast(1)
|
||||
return url.takeIf { it.length > "https://".length }
|
||||
}
|
||||
|
||||
private val ORDERED_ITEM = Regex("""^(\d{1,9})[.)]\s+(.*)$""")
|
||||
private val BULLET_ITEM = Regex("""^([-*+])\s+(.*)$""")
|
||||
|
||||
// ---- Renderers ---------------------------------------------------------------
|
||||
|
||||
private val MD_QUOTE_BAR = 3.dp
|
||||
private val MD_TABLE_BORDER = HAIRLINE_DP
|
||||
|
||||
/**
|
||||
* Renders [text] as markdown at the app's shared body style. The caller owns the
|
||||
* selection container (a chat message is one selectable region), so this only
|
||||
* lays out the blocks.
|
||||
*/
|
||||
@Composable
|
||||
internal fun MarkdownText(text: String, modifier: Modifier = Modifier) {
|
||||
val blocks = remember(text) { parseMarkdown(text) }
|
||||
Column(modifier, verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
|
||||
blocks.forEach { MarkdownBlock(it) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MarkdownBlock(block: MdBlock) {
|
||||
val texts = pipelinesText()
|
||||
when (block) {
|
||||
is MdHeading -> Text(
|
||||
text = inline(block.text),
|
||||
style = when (block.level) {
|
||||
1 -> MaterialTheme.typography.titleLarge
|
||||
2 -> MaterialTheme.typography.titleMedium
|
||||
else -> texts.cardTitle
|
||||
},
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
|
||||
is MdParagraph -> Text(text = inline(block.text), style = texts.body)
|
||||
|
||||
is MdCodeBlock -> CodeBlock(label = block.language.ifBlank { "code" }, text = block.code)
|
||||
|
||||
MdRule -> HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
|
||||
|
||||
is MdQuote -> Row(Modifier.height(IntrinsicSize.Min)) {
|
||||
Box(
|
||||
Modifier
|
||||
.width(MD_QUOTE_BAR)
|
||||
.fillMaxHeight()
|
||||
.background(MaterialTheme.colorScheme.outlineVariant),
|
||||
)
|
||||
Column(
|
||||
modifier = Modifier.padding(start = CHAT_ITEM_GAP),
|
||||
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP / 2),
|
||||
) {
|
||||
block.lines.forEach { line ->
|
||||
if (line.isNotBlank()) {
|
||||
Text(
|
||||
text = inline(line),
|
||||
style = texts.body,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is MdListBlock -> Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP / 2)) {
|
||||
block.items.forEachIndexed { index, item ->
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
|
||||
Text(
|
||||
text = if (block.ordered) "${index + 1}." else "•",
|
||||
style = texts.body,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(text = inline(item), style = texts.body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is MdTableBlock -> MarkdownTable(block)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MarkdownTable(table: MdTableBlock) {
|
||||
val border = MaterialTheme.colorScheme.outlineVariant
|
||||
val shape = RoundedCornerShape(CHAT_ITEM_GAP)
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(shape)
|
||||
.border(MD_TABLE_BORDER, border, shape),
|
||||
) {
|
||||
TableRow(table.header, header = true, border = border)
|
||||
table.rows.forEach { row ->
|
||||
HorizontalDivider(color = border)
|
||||
TableRow(row, header = false, border = border)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TableRow(cells: List<String>, header: Boolean, border: Color) {
|
||||
val texts = pipelinesText()
|
||||
Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
|
||||
cells.forEachIndexed { index, cell ->
|
||||
if (index > 0) {
|
||||
Box(Modifier.width(MD_TABLE_BORDER).fillMaxHeight().background(border))
|
||||
}
|
||||
Text(
|
||||
text = inline(cell),
|
||||
style = if (header) texts.body.copy(fontWeight = FontWeight.Bold) else texts.body,
|
||||
modifier = Modifier.weight(1f).padding(CHAT_ITEM_GAP),
|
||||
maxLines = if (header) 1 else Int.MAX_VALUE,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Inline text as one [AnnotatedString]; links are tappable and code is monospace. */
|
||||
@Composable
|
||||
private fun inline(text: String): AnnotatedString {
|
||||
val linkColor = MaterialTheme.colorScheme.primary
|
||||
val codeBackground = MaterialTheme.colorScheme.surfaceContainerHigh
|
||||
val codeColor = MaterialTheme.colorScheme.onSurface
|
||||
return remember(text, linkColor, codeBackground, codeColor) {
|
||||
buildInline(parseInline(text), linkColor, codeBackground, codeColor)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildInline(
|
||||
spans: List<MdSpan>,
|
||||
linkColor: Color,
|
||||
codeBackground: Color,
|
||||
codeColor: Color,
|
||||
): AnnotatedString = buildAnnotatedString { appendSpans(spans, linkColor, codeBackground, codeColor) }
|
||||
|
||||
private fun androidx.compose.ui.text.AnnotatedString.Builder.appendSpans(
|
||||
spans: List<MdSpan>,
|
||||
linkColor: Color,
|
||||
codeBackground: Color,
|
||||
codeColor: Color,
|
||||
) {
|
||||
for (span in spans) {
|
||||
when (span) {
|
||||
is MdPlain -> append(span.text)
|
||||
is MdCodeSpan -> withStyle(
|
||||
SpanStyle(fontFamily = FontFamily.Monospace, background = codeBackground, color = codeColor),
|
||||
) { append(span.text) }
|
||||
is MdStrong -> withStyle(SpanStyle(fontWeight = FontWeight.Bold)) {
|
||||
appendSpans(span.spans, linkColor, codeBackground, codeColor)
|
||||
}
|
||||
is MdEmphasis -> withStyle(SpanStyle(fontStyle = FontStyle.Italic)) {
|
||||
appendSpans(span.spans, linkColor, codeBackground, codeColor)
|
||||
}
|
||||
is MdLinkSpan -> withLink(
|
||||
LinkAnnotation.Url(
|
||||
span.url,
|
||||
TextLinkStyles(style = SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)),
|
||||
),
|
||||
) { appendSpans(span.spans, linkColor, codeBackground, codeColor) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -212,3 +212,18 @@ internal val STAGE_CHIP_PAD_H = 10.dp
|
||||
|
||||
/** The omni-search panel's inline progress spinner. */
|
||||
internal val SEARCH_PROGRESS_DP = 18.dp
|
||||
|
||||
/** The thinnest line the UI draws - a table border, a divider or a card outline. */
|
||||
internal val HAIRLINE_DP = 1.dp
|
||||
|
||||
/** A small icon button: the session close action and the tool-panel dismiss. */
|
||||
internal val ICON_BUTTON_SMALL_DP = 28.dp
|
||||
|
||||
/** The floating tool panel's maximum width; it floats over the transcript. */
|
||||
internal val TOOL_PANEL_MAX_WIDTH_DP = 420.dp
|
||||
|
||||
/** A chat row's title column stops here so the close action keeps its place. */
|
||||
internal val CHAT_TITLE_MAX_WIDTH_DP = 160.dp
|
||||
|
||||
/** A chat message bubble's maximum width, so long prose stays readable. */
|
||||
internal val CHAT_BUBBLE_MAX_WIDTH_DP = 560.dp
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
package net.awan.pipelines.data.protocol
|
||||
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ChatProtocolTest {
|
||||
|
||||
@Test
|
||||
fun chatSessionsParseWithBusyFlagAndFlattenedFields() {
|
||||
val json = """
|
||||
{
|
||||
"type": "chat_sessions",
|
||||
"id": "android-1",
|
||||
"chat_sessions": [
|
||||
{
|
||||
"id": "ses_abc",
|
||||
"title": "Fix the parser",
|
||||
"agent": "build",
|
||||
"model": "deepseek-v4.1-flash",
|
||||
"directory": "/Users/alan/repos/pipelines",
|
||||
"parent_id": "",
|
||||
"created_at": 1792112366711,
|
||||
"updated_at": 1792112367036,
|
||||
"busy": true
|
||||
},
|
||||
{"id": "ses_def", "title": "Second chat"}
|
||||
]
|
||||
}
|
||||
""".trimIndent()
|
||||
val message = PipelinesJson.decodeFromString(Message.serializer(), json)
|
||||
assertEquals(Protocol.CHAT_SESSIONS, message.type)
|
||||
val sessions = message.chatSessions!!
|
||||
assertEquals(2, sessions.size)
|
||||
val first = sessions.first()
|
||||
assertEquals("ses_abc", first.id)
|
||||
assertEquals("Fix the parser", first.title)
|
||||
assertEquals("/Users/alan/repos/pipelines", first.directory)
|
||||
assertEquals(1792112366711L, first.createdAt)
|
||||
assertTrue(first.busy)
|
||||
// An absent busy key defaults to false, never a crash.
|
||||
assertTrue(!sessions[1].busy)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun chatMessagesParseTextReasoningAndToolParts() {
|
||||
val json = """
|
||||
{
|
||||
"type": "chat_messages",
|
||||
"chat_messages": [
|
||||
{
|
||||
"id": "msg_user",
|
||||
"session_id": "ses_abc",
|
||||
"role": "user",
|
||||
"parts": [{"type": "text", "id": "p1", "text": "hello"}]
|
||||
},
|
||||
{
|
||||
"id": "msg_asst",
|
||||
"session_id": "ses_abc",
|
||||
"role": "assistant",
|
||||
"parts": [
|
||||
{"type": "reasoning", "id": "r1", "text": "thinking"},
|
||||
{"type": "text", "id": "t1", "text": "done"},
|
||||
{
|
||||
"type": "tool",
|
||||
"id": "call_1",
|
||||
"name": "shell",
|
||||
"executed": false,
|
||||
"state": {
|
||||
"status": "completed",
|
||||
"input": {"command": "ls"},
|
||||
"content": [{"type": "text", "text": "a.txt"}],
|
||||
"metadata": {"exit": 0},
|
||||
"error": null
|
||||
},
|
||||
"time": {"created": 10, "ran": 12, "completed": 20}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
""".trimIndent()
|
||||
val messages = PipelinesJson.decodeFromString(Message.serializer(), json).chatMessages!!
|
||||
assertEquals(2, messages.size)
|
||||
assertEquals(ChatProtocol.ROLE_USER, messages[0].role)
|
||||
assertEquals("hello", messages[0].parts.single().text)
|
||||
val assistant = messages[1]
|
||||
assertEquals(ChatProtocol.PART_REASONING, assistant.parts[0].type)
|
||||
val tool = assistant.parts.first { it.type == ChatProtocol.PART_TOOL }
|
||||
assertEquals("shell", tool.name)
|
||||
assertEquals(ChatProtocol.TOOL_COMPLETED, tool.state!!.status)
|
||||
assertTrue(tool.state!!.input is JsonObject)
|
||||
assertEquals("a.txt", tool.state!!.content.single().text)
|
||||
assertEquals(8L, toolDuration(tool))
|
||||
}
|
||||
|
||||
/** The tool input is a partial-JSON string while streaming and an object afterwards. */
|
||||
@Test
|
||||
fun streamingToolInputIsAStringAndCompletedInputIsAnObject() {
|
||||
val streaming = """
|
||||
{"type":"chat_event","chat_event":{"session_id":"ses_1","message_id":"m1","kind":"tool",
|
||||
"part":{"type":"tool","id":"c1","name":"edit","state":{"status":"streaming","input":"{\"old"}}}}
|
||||
""".trimIndent()
|
||||
val frame = PipelinesJson.decodeFromString(Message.serializer(), streaming).chatEvent!!
|
||||
assertEquals(ChatProtocol.TOOL_STREAMING, frame.part!!.state!!.status)
|
||||
assertEquals("{\"old", (frame.part!!.state!!.input as JsonPrimitive).content)
|
||||
assertTrue(ChatProtocol.toolRunning(frame.part!!.state))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun chatEventDeltaCarriesTheTargetPartAndText() {
|
||||
val json = """
|
||||
{"type":"chat_event","chat_event":{"session_id":"ses_1","message_id":"m1","kind":"text",
|
||||
"delta":"wor","part":{"type":"text","id":"t1"}}}
|
||||
""".trimIndent()
|
||||
val frame = PipelinesJson.decodeFromString(Message.serializer(), json).chatEvent!!
|
||||
assertEquals("ses_1", frame.sessionId)
|
||||
assertEquals("m1", frame.messageId)
|
||||
assertEquals(ChatProtocol.PART_TEXT, frame.kind)
|
||||
assertEquals("wor", frame.delta)
|
||||
assertEquals("t1", frame.part!!.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stepAndUsageFramesDecode() {
|
||||
val step = """
|
||||
{"type":"chat_event","chat_event":{"session_id":"s","kind":"step","step":{"status":"ended","index":3}}}
|
||||
""".trimIndent()
|
||||
val decodedStep = PipelinesJson.decodeFromString(Message.serializer(), step).chatEvent!!
|
||||
assertEquals(ChatProtocol.EVENT_STEP, decodedStep.kind)
|
||||
assertEquals(ChatProtocol.STEP_ENDED, decodedStep.step!!.status)
|
||||
|
||||
val usage = """
|
||||
{"type":"chat_event","chat_event":{"session_id":"s","kind":"usage",
|
||||
"usage":{"input_tokens":12,"output_tokens":34,"cost":0.002}}}
|
||||
""".trimIndent()
|
||||
val decodedUsage = PipelinesJson.decodeFromString(Message.serializer(), usage).chatEvent!!
|
||||
assertEquals(12, decodedUsage.usage!!.inputTokens)
|
||||
assertEquals(34, decodedUsage.usage!!.outputTokens)
|
||||
assertEquals(0.002, decodedUsage.usage!!.cost, 0.0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun chatPermissionFrameDecodesTheRequestShape() {
|
||||
val json = """
|
||||
{"type":"chat_permission","chat_permission":{"session_id":"ses_1","request_id":"req_9",
|
||||
"action":"edit","resources":["src/a.kt"],
|
||||
"source":{"type":"tool","message_id":"m1","id":"c1"},
|
||||
"message":"Allow this edit?"}}
|
||||
""".trimIndent()
|
||||
val permission = PipelinesJson.decodeFromString(Message.serializer(), json).chatPermission!!
|
||||
assertEquals("req_9", permission.requestId)
|
||||
assertEquals("edit", permission.action)
|
||||
assertEquals("src/a.kt", permission.resources.single())
|
||||
assertEquals("c1", permission.source!!.id)
|
||||
// An open request defaults to unresolved; nothing is invented.
|
||||
assertTrue(!permission.resolved)
|
||||
assertEquals("", permission.decision)
|
||||
}
|
||||
|
||||
/** A request the server reports as already settled carries the outcome. */
|
||||
@Test
|
||||
fun chatPermissionFrameCarriesTheServerResolution() {
|
||||
val json = """
|
||||
{"type":"chat_permission","chat_permission":{"session_id":"ses_1","request_id":"req_9",
|
||||
"action":"edit","resolved":true,"decision":"reject","message":"another client rejected it"}}
|
||||
""".trimIndent()
|
||||
val permission = PipelinesJson.decodeFromString(Message.serializer(), json).chatPermission!!
|
||||
assertTrue(permission.resolved)
|
||||
assertEquals(ChatProtocol.DECISION_REJECT, permission.decision)
|
||||
assertEquals("another client rejected it", permission.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun chatRequestsRoundTripTheirBodies() {
|
||||
val create = Message(
|
||||
type = Protocol.CHAT_CREATE,
|
||||
id = "android-1",
|
||||
chatCreate = ChatCreateRequest(title = "New chat", directory = "/work"),
|
||||
)
|
||||
val createJson = PipelinesJson.encodeToString(Message.serializer(), create)
|
||||
assertTrue(createJson.contains("\"chat_create\""))
|
||||
val decodedCreate = PipelinesJson.decodeFromString(Message.serializer(), createJson)
|
||||
assertEquals("New chat", decodedCreate.chatCreate!!.title)
|
||||
|
||||
val prompt = Message(
|
||||
type = Protocol.CHAT_PROMPT,
|
||||
id = "android-2",
|
||||
chatPrompt = ChatPromptRequest(sessionId = "ses_1", text = "hi"),
|
||||
)
|
||||
val decodedPrompt = PipelinesJson.decodeFromString(
|
||||
Message.serializer(),
|
||||
PipelinesJson.encodeToString(Message.serializer(), prompt),
|
||||
)
|
||||
assertEquals("ses_1", decodedPrompt.chatPrompt!!.sessionId)
|
||||
assertEquals("hi", decodedPrompt.chatPrompt!!.text)
|
||||
|
||||
val query = Message(type = Protocol.CHAT_MESSAGES, id = "android-3", chatQuery = ChatQuery("ses_1", 50))
|
||||
val decodedQuery = PipelinesJson.decodeFromString(
|
||||
Message.serializer(),
|
||||
PipelinesJson.encodeToString(Message.serializer(), query),
|
||||
)
|
||||
assertEquals("ses_1", decodedQuery.chatQuery!!.sessionId)
|
||||
assertEquals(50, decodedQuery.chatQuery!!.limit)
|
||||
|
||||
val reply = Message(
|
||||
type = Protocol.CHAT_REPLY,
|
||||
id = "android-4",
|
||||
chatReply = ChatReplyRequest("ses_1", "req_9", ChatProtocol.DECISION_ONCE),
|
||||
)
|
||||
val decodedReply = PipelinesJson.decodeFromString(
|
||||
Message.serializer(),
|
||||
PipelinesJson.encodeToString(Message.serializer(), reply),
|
||||
)
|
||||
assertEquals(ChatProtocol.DECISION_ONCE, decodedReply.chatReply!!.decision)
|
||||
}
|
||||
|
||||
/**
|
||||
* The stop control's interrupt request: pressing it while a turn is in flight
|
||||
* must send a `chat_interrupt` carrying the running session's id and nothing
|
||||
* else, and the frame must survive the wire round-trip the client performs.
|
||||
* Uses the same [ChatProtocol.interruptRequest] builder the repository sends,
|
||||
* so this test cannot drift from the production frame.
|
||||
*/
|
||||
@Test
|
||||
fun chatInterruptRequestCarriesTheRunningSession() {
|
||||
val request = ChatProtocol.interruptRequest("ses_1")
|
||||
assertEquals(Protocol.CHAT_INTERRUPT, request.type)
|
||||
assertEquals("ses_1", request.chatQuery!!.sessionId)
|
||||
|
||||
val encoded = PipelinesJson.encodeToString(Message.serializer(), request.copy(id = "android-9"))
|
||||
val decoded = PipelinesJson.decodeFromString(Message.serializer(), encoded)
|
||||
assertEquals(Protocol.CHAT_INTERRUPT, decoded.type)
|
||||
assertEquals("ses_1", decoded.chatQuery!!.sessionId)
|
||||
assertNull(decoded.chatPrompt)
|
||||
assertNull(decoded.chatReply)
|
||||
}
|
||||
|
||||
/** A non-chat envelope leaves every chat field null, so the two never cross-talk. */
|
||||
@Test
|
||||
fun nonChatEnvelopeHasNoChatPayload() {
|
||||
val message = PipelinesJson.decodeFromString(
|
||||
Message.serializer(),
|
||||
"""{"type":"pong"}""",
|
||||
)
|
||||
assertNull(message.chatEvent)
|
||||
assertNull(message.chatSessions)
|
||||
assertNull(message.chatPermission)
|
||||
}
|
||||
|
||||
private fun toolDuration(part: ChatPart): Long? {
|
||||
val time = part.time ?: return null
|
||||
return time.completed - time.ran
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import net.awan.pipelines.data.protocol.ChatPermissionFrame
|
||||
import net.awan.pipelines.data.protocol.ChatProtocol
|
||||
import net.awan.pipelines.data.protocol.ChatSession
|
||||
import net.awan.pipelines.data.protocol.Message
|
||||
import net.awan.pipelines.data.protocol.PipelinesJson
|
||||
import net.awan.pipelines.data.protocol.Protocol
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* The approval card the conversation shows for a pushed permission request: the
|
||||
* request appears as a card, answering it updates the card in place with the
|
||||
* decision the reply frame carries, and a request the server reports as already
|
||||
* resolved offers no stale actions. Driven through [ChatStore] and the pure
|
||||
* [approvalCard] the composable renders, so no device, server or Compose runtime
|
||||
* is needed.
|
||||
*/
|
||||
class ChatApprovalTest {
|
||||
|
||||
private fun frame(
|
||||
requestId: String = "req_9",
|
||||
action: String = "edit",
|
||||
resources: List<String> = listOf("src/a.kt"),
|
||||
message: String = "This edits a file in your workspace.",
|
||||
resolved: Boolean = false,
|
||||
decision: String = "",
|
||||
) = ChatPermissionFrame(
|
||||
sessionId = "ses_1",
|
||||
requestId = requestId,
|
||||
action = action,
|
||||
resources = resources,
|
||||
message = message,
|
||||
resolved = resolved,
|
||||
decision = decision,
|
||||
)
|
||||
|
||||
private fun storeWithPermission(permission: ChatPermissionFrame): ChatStore {
|
||||
val store = ChatStore()
|
||||
store.open(ChatSession(id = "ses_1", title = "Chat"))
|
||||
store.permission(permission)
|
||||
return store
|
||||
}
|
||||
|
||||
private fun card(store: ChatStore): ApprovalCard {
|
||||
val thread = store.value.thread("ses_1")!!
|
||||
return approvalCard(thread.permission, thread.permissionAnswer)!!
|
||||
}
|
||||
|
||||
@Test
|
||||
fun permissionFrameShowsAPendingApprovalCard() {
|
||||
val card = card(storeWithPermission(frame()))
|
||||
|
||||
assertEquals(ApprovalState.PENDING, card.state)
|
||||
assertTrue(card.actionable)
|
||||
assertEquals("Approve edit", card.headline)
|
||||
assertEquals("Waiting for your response", card.statusLine)
|
||||
assertEquals(listOf("src/a.kt"), card.resources)
|
||||
assertEquals("This edits a file in your workspace.", card.risk)
|
||||
assertTrue(card.showRisk)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onceAlwaysAndRejectSendTheRightDecision() {
|
||||
// The same builder the repository sends, so the card's actions and this
|
||||
// assertion cannot drift from the wire frame. Every decision goes through
|
||||
// the identical encode/decode round trip, so none is asserted more weakly
|
||||
// than another.
|
||||
for (decision in listOf(
|
||||
ChatProtocol.DECISION_ONCE,
|
||||
ChatProtocol.DECISION_ALWAYS,
|
||||
ChatProtocol.DECISION_REJECT,
|
||||
)) {
|
||||
val reply = ChatProtocol.replyRequest("ses_1", "req_9", decision)
|
||||
assertEquals(Protocol.CHAT_REPLY, reply.type)
|
||||
assertEquals("ses_1", reply.chatReply!!.sessionId)
|
||||
assertEquals("req_9", reply.chatReply!!.requestId)
|
||||
assertEquals(decision, reply.chatReply!!.decision)
|
||||
|
||||
val decoded = PipelinesJson.decodeFromString(
|
||||
Message.serializer(),
|
||||
PipelinesJson.encodeToString(Message.serializer(), reply.copy(id = "android-1")),
|
||||
)
|
||||
assertEquals(decision, decoded.chatReply!!.decision)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun answeringOnceUpdatesTheCardInPlace() {
|
||||
val store = storeWithPermission(frame())
|
||||
store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_ONCE)
|
||||
|
||||
val settled = card(store)
|
||||
assertEquals(ApprovalState.ANSWERED, settled.state)
|
||||
assertFalse(settled.actionable)
|
||||
assertEquals(ChatProtocol.DECISION_ONCE, settled.decision)
|
||||
assertEquals("Allowed once", settled.headline)
|
||||
// The request is still on screen, not removed: it just stopped asking.
|
||||
assertEquals("req_9", store.value.thread("ses_1")!!.permission!!.requestId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun answeringAlwaysUpdatesTheCardInPlace() {
|
||||
val store = storeWithPermission(frame())
|
||||
store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_ALWAYS)
|
||||
|
||||
val settled = card(store)
|
||||
assertEquals(ApprovalState.ANSWERED, settled.state)
|
||||
assertFalse(settled.actionable)
|
||||
assertEquals(ChatProtocol.DECISION_ALWAYS, settled.decision)
|
||||
assertEquals("Always allowed", settled.headline)
|
||||
// The request stays visible but stops asking; only a denial keeps the
|
||||
// amber review panel, so an allow-always retires it.
|
||||
assertFalse(settled.showRisk)
|
||||
assertEquals("req_9", store.value.thread("ses_1")!!.permission!!.requestId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectingKeepsTheRiskReviewWhileItSettles() {
|
||||
val store = storeWithPermission(frame())
|
||||
store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_REJECT)
|
||||
|
||||
val settled = card(store)
|
||||
assertEquals(ApprovalState.ANSWERED, settled.state)
|
||||
assertEquals("Rejected", settled.headline)
|
||||
assertTrue(settled.showRisk)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun serverResolvedRequestOffersNoActions() {
|
||||
val store = storeWithPermission(frame(resolved = true, message = "Another client already answered."))
|
||||
|
||||
val resolved = card(store)
|
||||
assertEquals(ApprovalState.RESOLVED, resolved.state)
|
||||
assertFalse(resolved.actionable)
|
||||
assertEquals("Already resolved", resolved.headline)
|
||||
assertEquals("Another client already answered.", resolved.statusLine)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun serverResolvedDecisionIsNamed() {
|
||||
val store = storeWithPermission(
|
||||
frame(resolved = true, decision = ChatProtocol.DECISION_REJECT, message = ""),
|
||||
)
|
||||
assertEquals("Rejected", card(store).headline)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failedReplyReopensTheRequest() {
|
||||
val store = storeWithPermission(frame())
|
||||
store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_ONCE)
|
||||
store.permissionReplyFailed("ses_1", "req_9")
|
||||
assertTrue(card(store).actionable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun riskFallsBackToTheActionWhenTheServerSendsNoSummary() {
|
||||
val store = storeWithPermission(frame(message = "", resources = emptyList()))
|
||||
val card = card(store)
|
||||
assertTrue(card.risk.contains("edit"))
|
||||
assertEquals(emptyList<String>(), card.resources)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRequestWithoutAnIdShowsNoCard() {
|
||||
val store = storeWithPermission(frame(requestId = ""))
|
||||
val thread = store.value.thread("ses_1")!!
|
||||
assertNull(approvalCard(thread.permission, thread.permissionAnswer))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import net.awan.pipelines.data.protocol.ChatError
|
||||
import net.awan.pipelines.data.protocol.ChatPart
|
||||
import net.awan.pipelines.data.protocol.ChatProtocol
|
||||
import net.awan.pipelines.data.protocol.ChatSession
|
||||
import net.awan.pipelines.data.protocol.ChatTime
|
||||
import net.awan.pipelines.data.protocol.ChatToolContent
|
||||
import net.awan.pipelines.data.protocol.ChatToolState
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ChatFormatTest {
|
||||
|
||||
@Test
|
||||
fun prettyToolInputPrintsObjectsAndPassesThroughPartialStrings() {
|
||||
val obj = prettyToolInput(JsonObject(mapOf("command" to JsonPrimitive("ls"))))
|
||||
assertTrue(obj.contains("\"command\""))
|
||||
assertTrue(obj.contains("\n"))
|
||||
assertEquals("{\"old", prettyToolInput(JsonPrimitive("{\"old")))
|
||||
assertEquals("", prettyToolInput(null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toolOutputFallsBackToNoOutput() {
|
||||
val completed = ChatToolState(
|
||||
status = ChatProtocol.TOOL_COMPLETED,
|
||||
content = listOf(ChatToolContent(type = "text", text = "hello")),
|
||||
)
|
||||
assertEquals("hello", toolOutputText(completed))
|
||||
assertEquals(
|
||||
"(no output)",
|
||||
toolOutputText(ChatToolState(status = ChatProtocol.TOOL_COMPLETED)),
|
||||
)
|
||||
// Still streaming -> nothing yet, never the "(no output)" claim.
|
||||
assertEquals("", toolOutputText(ChatToolState(status = ChatProtocol.TOOL_RUNNING)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toolErrorPrefersTheMessageOverPartialOutput() {
|
||||
// A failed call can carry both output content and an error; the ERROR
|
||||
// block must show the message, never the output text.
|
||||
val failed = ChatToolState(
|
||||
status = ChatProtocol.TOOL_ERROR,
|
||||
content = listOf(ChatToolContent(type = "text", text = "partial output")),
|
||||
error = ChatError(type = "boom", message = "exploded"),
|
||||
)
|
||||
assertEquals("exploded", toolErrorText(failed))
|
||||
// A failure with no message still renders something rather than a blank block.
|
||||
assertEquals("(no output)", toolErrorText(ChatToolState(status = ChatProtocol.TOOL_ERROR)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toolDurationUsesRanToCompletedAndIsNullWhileRunning() {
|
||||
val done = ChatPart(name = "shell", time = ChatTime(created = 5, ran = 10, completed = 35))
|
||||
assertEquals(25L, toolDurationMillis(done))
|
||||
assertNull(toolDurationMillis(ChatPart(name = "shell", time = ChatTime(created = 5))))
|
||||
assertEquals("340ms", formatToolDuration(340))
|
||||
assertEquals("1.5s", formatToolDuration(1500))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sessionStatusReportsRunningBusyAndIdle() {
|
||||
assertEquals("Running", sessionStatusLabel(ChatSession(id = "s"), runningLocally = true))
|
||||
assertEquals(
|
||||
"Busy · read-only",
|
||||
sessionStatusLabel(ChatSession(id = "s", busy = true), runningLocally = false),
|
||||
)
|
||||
assertEquals("Idle", sessionStatusLabel(ChatSession(id = "s"), runningLocally = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun composerControlIsStopWhileARunIsInFlightAndSendOtherwise() {
|
||||
// While a turn is in flight the send control becomes the stop control:
|
||||
// the phone's composer offers the interrupt, never a second send.
|
||||
assertEquals(ComposerAction.Stop, composerAction(ChatThread(sessionId = "s", running = true)))
|
||||
assertEquals(ComposerAction.Send, composerAction(ChatThread(sessionId = "s")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toolEditDiffMarksOnlyChangedLinesAndCountsThem() {
|
||||
val input = JsonObject(
|
||||
mapOf(
|
||||
"filePath" to JsonPrimitive("/tmp/a.txt"),
|
||||
"oldString" to JsonPrimitive("one\ntwo\nthree"),
|
||||
"newString" to JsonPrimitive("one\nTWO\nthree\nfour"),
|
||||
),
|
||||
)
|
||||
val diff = toolEditDiff(input)!!
|
||||
assertEquals("/tmp/a.txt", diff.file)
|
||||
assertEquals(2, diff.added)
|
||||
assertEquals(1, diff.removed)
|
||||
// A small edit is shown whole, nothing summarised.
|
||||
assertEquals(0, diff.omitted)
|
||||
assertEquals(
|
||||
listOf(
|
||||
DiffLine(DiffKind.CONTEXT, "one"),
|
||||
DiffLine(DiffKind.REMOVE, "two"),
|
||||
DiffLine(DiffKind.ADD, "TWO"),
|
||||
DiffLine(DiffKind.CONTEXT, "three"),
|
||||
DiffLine(DiffKind.ADD, "four"),
|
||||
),
|
||||
diff.lines,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toolEditDiffSummarisesAnOversizedEditInsteadOfRenderingEveryLine() {
|
||||
// Wholly disjoint old/new blocks: every line is a change, so the full diff
|
||||
// is twice the block size — far past what a phone should render.
|
||||
val changed = MAX_RENDERED_DIFF_LINES + 50
|
||||
val old = (1..changed).joinToString("\n") { "old $it" }
|
||||
val new = (1..changed).joinToString("\n") { "new $it" }
|
||||
val diff = toolEditDiff(
|
||||
JsonObject(
|
||||
mapOf(
|
||||
"filePath" to JsonPrimitive("/tmp/big.txt"),
|
||||
"oldString" to JsonPrimitive(old),
|
||||
"newString" to JsonPrimitive(new),
|
||||
),
|
||||
),
|
||||
)!!
|
||||
// The stat still describes the whole edit...
|
||||
assertEquals(changed, diff.added)
|
||||
assertEquals(changed, diff.removed)
|
||||
// ...but only a readable prefix is rendered, the rest counted as omitted.
|
||||
assertEquals(MAX_RENDERED_DIFF_LINES, diff.lines.size)
|
||||
assertEquals(2 * changed - MAX_RENDERED_DIFF_LINES, diff.omitted)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toolEditDiffIsNullForNonEdits() {
|
||||
assertNull(toolEditDiff(null))
|
||||
assertNull(toolEditDiff(JsonObject(mapOf("command" to JsonPrimitive("ls")))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toolFailedOnlyForTheErrorStatus() {
|
||||
assertTrue(toolFailed(ChatToolState(status = ChatProtocol.TOOL_ERROR)))
|
||||
assertFalse(toolFailed(ChatToolState(status = ChatProtocol.TOOL_COMPLETED)))
|
||||
assertFalse(toolFailed(ChatToolState(status = ChatProtocol.TOOL_RUNNING)))
|
||||
assertFalse(toolFailed(null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sessionTitleNeverBlank() {
|
||||
assertEquals("Named", sessionTitle(ChatSession(id = "ses_1", title = "Named")))
|
||||
assertEquals("ses_abcdefghijklmn", sessionTitle(ChatSession(id = "ses_abcdefghijklmnop")))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import net.awan.pipelines.data.protocol.ChatEventFrame
|
||||
import net.awan.pipelines.data.protocol.ChatPart
|
||||
import net.awan.pipelines.data.protocol.ChatProtocol
|
||||
import net.awan.pipelines.data.protocol.ChatSession
|
||||
import net.awan.pipelines.data.protocol.ChatStep
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* The streaming guarantees: a sequence of text deltas grows the rendered
|
||||
* conversation and the running indicator toggles on and off, the elapsed time is
|
||||
* derived from the turn's own start, a reconnect settles the indicator before the
|
||||
* history re-fetch, and a mid-stream failure settles it with the server's text.
|
||||
* Driven directly against [ChatStore] with an injected clock, so no device,
|
||||
* server or Compose runtime is needed.
|
||||
*/
|
||||
class ChatStreamTest {
|
||||
|
||||
private fun session(id: String) = ChatSession(id = id, title = id)
|
||||
|
||||
private fun step(status: String) = ChatEventFrame(
|
||||
sessionId = "s",
|
||||
kind = ChatProtocol.EVENT_STEP,
|
||||
step = ChatStep(status = status),
|
||||
)
|
||||
|
||||
private fun delta(sessionId: String, messageId: String, partId: String, text: String) = ChatEventFrame(
|
||||
sessionId = sessionId,
|
||||
messageId = messageId,
|
||||
kind = ChatProtocol.PART_TEXT,
|
||||
delta = text,
|
||||
part = ChatPart(type = ChatProtocol.PART_TEXT, id = partId),
|
||||
)
|
||||
|
||||
/** The text of the single assistant message, exactly what the transcript renders. */
|
||||
private fun renderedText(store: ChatStore, sessionId: String): String =
|
||||
store.value.thread(sessionId)!!.messages.last().parts.single().text
|
||||
|
||||
@Test
|
||||
fun deltaSequenceGrowsRenderedTextAndTogglesRunning() {
|
||||
val store = ChatStore()
|
||||
store.open(session("s"))
|
||||
store.history("s", emptyList())
|
||||
assertFalse(store.value.thread("s")!!.running)
|
||||
|
||||
// A step starting the turn raises the running indicator.
|
||||
store.event(step(ChatProtocol.STEP_STARTED))
|
||||
assertTrue(store.value.thread("s")!!.running)
|
||||
|
||||
// Each delta appends to the same part: the rendered text is the exact
|
||||
// concatenation and strictly grows, never resets.
|
||||
val chunks = listOf("Hel", "lo ", "wor", "ld")
|
||||
val lengths = mutableListOf<Int>()
|
||||
chunks.forEachIndexed { index, chunk ->
|
||||
store.event(delta("s", "m1", "m1#0", chunk))
|
||||
assertEquals(chunks.take(index + 1).joinToString(""), renderedText(store, "s"))
|
||||
lengths += renderedText(store, "s").length
|
||||
}
|
||||
assertTrue(lengths.zipWithNext().all { (before, after) -> after > before })
|
||||
|
||||
// The step ending the turn lowers the indicator and clears its start.
|
||||
store.event(step(ChatProtocol.STEP_ENDED))
|
||||
assertFalse(store.value.thread("s")!!.running)
|
||||
assertEquals(0L, store.value.thread("s")!!.runningSince)
|
||||
assertEquals("Hello world", renderedText(store, "s"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun elapsedTimeComesFromTheTurnStartAndSurvivesARepeatedStart() {
|
||||
var clock = 1_000L
|
||||
val store = ChatStore(now = { clock })
|
||||
store.open(session("s"))
|
||||
|
||||
store.event(step(ChatProtocol.STEP_STARTED))
|
||||
assertEquals(1_000L, store.value.thread("s")!!.runningSince)
|
||||
|
||||
clock = 6_500L
|
||||
assertEquals(5_500L, store.value.thread("s")!!.elapsedMillis(clock))
|
||||
|
||||
// A second start for the same turn must not move the clock forward.
|
||||
store.event(step(ChatProtocol.STEP_STARTED))
|
||||
assertEquals(1_000L, store.value.thread("s")!!.runningSince)
|
||||
assertEquals(5_500L, store.value.thread("s")!!.elapsedMillis(clock))
|
||||
|
||||
// Settling drops the elapsed to 0 whatever the clock reads.
|
||||
store.event(step(ChatProtocol.STEP_ENDED))
|
||||
assertEquals(0L, store.value.thread("s")!!.elapsedMillis(clock))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun streamResumedSettlesRunningAndReturnsEveryOpenChat() {
|
||||
val store = ChatStore()
|
||||
store.open(session("a"))
|
||||
store.history("a", emptyList())
|
||||
store.open(session("b"))
|
||||
store.history("b", emptyList())
|
||||
store.running("a", true)
|
||||
|
||||
// A reconnect names every open chat so the caller re-fetches each, and no
|
||||
// thread keeps claiming to run until a fresh frame proves it.
|
||||
assertEquals(listOf("a", "b"), store.streamResumed())
|
||||
assertFalse(store.value.thread("a")!!.running)
|
||||
|
||||
// A delta after the resync re-asserts the running indicator.
|
||||
store.event(delta("a", "m1", "m1#0", "still going"))
|
||||
assertTrue(store.value.thread("a")!!.running)
|
||||
assertEquals("still going", renderedText(store, "a"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun streamErrorSettlesTheRunningTurnAndKeepsTheServerText() {
|
||||
val store = ChatStore()
|
||||
store.open(session("s"))
|
||||
store.running("s", true)
|
||||
|
||||
store.streamError("chat stream: boom")
|
||||
val thread = store.value.thread("s")!!
|
||||
assertFalse(thread.running)
|
||||
assertEquals("chat stream: boom", thread.error)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun streamErrorWithNothingRunningIsIgnored() {
|
||||
val store = ChatStore()
|
||||
store.open(session("s"))
|
||||
store.streamError("chat stream: boom")
|
||||
assertEquals(null, store.value.thread("s")!!.error)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class MarkdownTest {
|
||||
|
||||
@Test
|
||||
fun fencedCodeKeepsTheLanguageAndBody() {
|
||||
val blocks = parseMarkdown(
|
||||
"""
|
||||
Intro text.
|
||||
|
||||
```kotlin
|
||||
val gap = 8.dp
|
||||
println(gap)
|
||||
```
|
||||
""".trimIndent(),
|
||||
)
|
||||
assertEquals(MdParagraph("Intro text."), blocks[0])
|
||||
val code = blocks[1] as MdCodeBlock
|
||||
assertEquals("kotlin", code.language)
|
||||
assertEquals("val gap = 8.dp\nprintln(gap)", code.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUnterminatedFenceStillYieldsItsCode() {
|
||||
val blocks = parseMarkdown("```\nline one\nline two")
|
||||
val code = blocks.single() as MdCodeBlock
|
||||
assertEquals("", code.language)
|
||||
assertEquals("line one\nline two", code.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun softWrappedParagraphLinesJoinWithASpace() {
|
||||
assertEquals(listOf(MdParagraph("one two three")), parseMarkdown("one\ntwo\nthree"))
|
||||
assertEquals(listOf(MdParagraph("one"), MdParagraph("two")), parseMarkdown("one\n\ntwo"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun headingsAndThematicRulesParseByLevel() {
|
||||
val blocks = parseMarkdown("# Title\n\n## Section\n\n---")
|
||||
assertEquals(MdHeading(1, "Title"), blocks[0])
|
||||
assertEquals(MdHeading(2, "Section"), blocks[1])
|
||||
assertEquals(MdRule, blocks[2])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bulletAndOrderedListsKeepTheirOrder() {
|
||||
val bullets = parseMarkdown("- one\n- two").single() as MdListBlock
|
||||
assertEquals(false, bullets.ordered)
|
||||
assertEquals(listOf("one", "two"), bullets.items)
|
||||
|
||||
val ordered = parseMarkdown("1. first\n2. second").single() as MdListBlock
|
||||
assertEquals(true, ordered.ordered)
|
||||
assertEquals(listOf("first", "second"), ordered.items)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPipeTableParsesHeaderAndRows() {
|
||||
val blocks = parseMarkdown("| Name | Value |\n| --- | ---: |\n| a | 1 |\n| b | 2 |")
|
||||
val table = blocks.single() as MdTableBlock
|
||||
assertEquals(listOf("Name", "Value"), table.header)
|
||||
assertEquals(listOf(listOf("a", "1"), listOf("b", "2")), table.rows)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun inlineCodeBoldItalicAndLinksBecomeSpans() {
|
||||
val spans = parseInline("Use `CodeBlock` and **bold** and *italic* and [docs](https://example.com/x).")
|
||||
assertTrue(spans.any { it is MdCodeSpan && it.text == "CodeBlock" })
|
||||
assertTrue(spans.any { it is MdStrong })
|
||||
assertTrue(spans.any { it is MdEmphasis })
|
||||
val link = spans.filterIsInstance<MdLinkSpan>().single()
|
||||
assertEquals("https://example.com/x", link.url)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bareUrlsAutolinkAndTrimTrailingPunctuation() {
|
||||
val spans = parseInline("See https://example.com/a, then stop.")
|
||||
val link = spans.filterIsInstance<MdLinkSpan>().single()
|
||||
assertEquals("https://example.com/a", link.url)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun underscoresInsideAWordAreNotEmphasis() {
|
||||
assertEquals(listOf(MdPlain("snake_case_name")), parseInline("snake_case_name"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anEmptySourceParsesToNoBlocks() {
|
||||
assertEquals(emptyList<MdBlock>(), parseMarkdown(""))
|
||||
assertEquals(emptyList<MdBlock>(), parseMarkdown("\n\n"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import net.awan.pipelines.data.protocol.ChatEventFrame
|
||||
import net.awan.pipelines.data.protocol.ChatMessage
|
||||
import net.awan.pipelines.data.protocol.ChatPart
|
||||
import net.awan.pipelines.data.protocol.ChatPermissionFrame
|
||||
import net.awan.pipelines.data.protocol.ChatProtocol
|
||||
import net.awan.pipelines.data.protocol.ChatSession
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* The multi-chat state guarantees: each open chat preserves its own conversation,
|
||||
* a running session re-syncs when the operator returns to it, and the draft and
|
||||
* scroll position are per chat. Driven directly against [ChatStore], with no
|
||||
* device, server or Compose runtime.
|
||||
*/
|
||||
class MultiChatStateTest {
|
||||
|
||||
private fun session(id: String, title: String = id, busy: Boolean = false) =
|
||||
ChatSession(id = id, title = title, busy = busy)
|
||||
|
||||
private fun text(id: String, role: String, body: String) = ChatMessage(
|
||||
id = id,
|
||||
sessionId = "",
|
||||
role = role,
|
||||
parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, id = "$id-p", text = body)),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun switchingPreservesEachConversation() {
|
||||
val store = ChatStore()
|
||||
assertTrue(store.open(session("a", "Chat A")))
|
||||
store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "first"), text("a2", ChatProtocol.ROLE_ASSISTANT, "reply A")))
|
||||
|
||||
assertTrue(store.open(session("b", "Chat B")))
|
||||
store.history("b", listOf(text("b1", ChatProtocol.ROLE_USER, "different")))
|
||||
|
||||
// Returning to A shows A's conversation, untouched by B. A loaded,
|
||||
// settled chat needs no re-sync.
|
||||
assertFalse(store.activate("a"))
|
||||
assertEquals(listOf("a1", "a2"), store.value.thread("a")!!.messages.map { it.id })
|
||||
assertEquals("a", store.value.activeId)
|
||||
|
||||
assertFalse(store.activate("b"))
|
||||
assertEquals(listOf("b1"), store.value.thread("b")!!.messages.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun runningSessionResyncsOnReturn() {
|
||||
val store = ChatStore()
|
||||
store.open(session("a"))
|
||||
store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "prompt")))
|
||||
store.running("a", true)
|
||||
store.open(session("b"))
|
||||
store.history("b", emptyList())
|
||||
|
||||
// Switching to B must not cancel A's running turn.
|
||||
store.activate("b")
|
||||
assertTrue(store.value.thread("a")!!.running)
|
||||
|
||||
// Returning to the running chat reports that it must be re-synced.
|
||||
assertTrue(store.activate("a"))
|
||||
|
||||
// The re-sync replaces the conversation with the server's copy and keeps running.
|
||||
store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "prompt"), text("a2", ChatProtocol.ROLE_ASSISTANT, "live")))
|
||||
val resynced = store.value.thread("a")!!
|
||||
assertTrue(resynced.running)
|
||||
assertEquals("live", resynced.messages.last().parts.single().text)
|
||||
// Once it settles, a later return does not force another re-sync.
|
||||
store.running("a", false)
|
||||
store.activate("b")
|
||||
assertFalse(store.activate("a"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun draftsArePerChat() {
|
||||
val store = ChatStore()
|
||||
store.open(session("a"))
|
||||
store.open(session("b"))
|
||||
|
||||
store.draft("a", "hello from A")
|
||||
store.draft("b", "typed in B")
|
||||
|
||||
store.activate("a")
|
||||
assertEquals("hello from A", store.value.thread("a")!!.draft)
|
||||
store.activate("b")
|
||||
assertEquals("typed in B", store.value.thread("b")!!.draft)
|
||||
|
||||
// Clearing one chat's draft never touches the other's.
|
||||
store.clearDraft("b")
|
||||
assertEquals("", store.value.thread("b")!!.draft)
|
||||
assertEquals("hello from A", store.value.thread("a")!!.draft)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun scrollPositionIsPerChat() {
|
||||
val store = ChatStore()
|
||||
store.open(session("a"))
|
||||
store.open(session("b"))
|
||||
store.scroll("a", 7, 12)
|
||||
store.scroll("b", 1, 0)
|
||||
assertEquals(ChatScrollPosition(7, 12), store.value.thread("a")!!.scroll)
|
||||
assertEquals(ChatScrollPosition(1, 0), store.value.thread("b")!!.scroll)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun busySessionIsReadOnlyAndCannotSend() {
|
||||
val store = ChatStore()
|
||||
store.open(session("a", busy = true))
|
||||
store.draft("a", "unsent")
|
||||
val thread = store.value.thread("a")!!
|
||||
assertTrue(thread.readOnly)
|
||||
assertFalse(thread.canSend)
|
||||
|
||||
// The server can clear busy later; the chat then becomes writable again.
|
||||
store.sessionsLoaded(listOf(session("a", busy = false)))
|
||||
store.draft("a", "unsent")
|
||||
assertFalse(store.value.thread("a")!!.readOnly)
|
||||
assertTrue(store.value.thread("a")!!.canSend)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sessionsLoadedMergesStatusWithoutDroppingOpenConversations() {
|
||||
val store = ChatStore()
|
||||
store.open(session("a", "Chat A"))
|
||||
store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "keep me")))
|
||||
// The server now reports A busy and adds a new session B.
|
||||
store.sessionsLoaded(listOf(session("a", "Chat A renamed", busy = true), session("b", "Chat B")))
|
||||
|
||||
val thread = store.value.thread("a")!!
|
||||
assertEquals("Chat A renamed", thread.title)
|
||||
assertTrue(thread.busy)
|
||||
assertEquals(listOf("a1"), thread.messages.map { it.id })
|
||||
assertEquals(2, store.value.sessions.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun backgroundEventsApplyToTheirChatAndCreateAPlaceholder() {
|
||||
val store = ChatStore()
|
||||
store.open(session("a"))
|
||||
store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "go")))
|
||||
store.open(session("b")) // B is active
|
||||
|
||||
// A delta for the background chat A lands on A, not on B, and B stays active.
|
||||
store.event(
|
||||
ChatEventFrame(
|
||||
sessionId = "a",
|
||||
messageId = "a2",
|
||||
kind = ChatProtocol.PART_TEXT,
|
||||
delta = "streaming",
|
||||
part = ChatPart(type = ChatProtocol.PART_TEXT, id = "a2-p"),
|
||||
),
|
||||
)
|
||||
assertEquals("streaming", store.value.thread("a")!!.messages.last().parts.single().text)
|
||||
assertEquals("b", store.value.activeId)
|
||||
|
||||
// A frame for a chat that was never opened creates a placeholder thread.
|
||||
store.event(
|
||||
ChatEventFrame(
|
||||
sessionId = "c",
|
||||
messageId = "c1",
|
||||
kind = ChatProtocol.PART_TEXT,
|
||||
delta = "hi",
|
||||
part = ChatPart(type = ChatProtocol.PART_TEXT, id = "c1-p"),
|
||||
),
|
||||
)
|
||||
assertNotNull(store.value.thread("c"))
|
||||
assertEquals("hi", store.value.thread("c")!!.messages.single().parts.single().text)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stepFramesTrackRunningState() {
|
||||
val store = ChatStore()
|
||||
store.open(session("a"))
|
||||
store.event(ChatEventFrame(sessionId = "a", kind = ChatProtocol.EVENT_STEP, step = net.awan.pipelines.data.protocol.ChatStep(status = ChatProtocol.STEP_STARTED)))
|
||||
assertTrue(store.value.thread("a")!!.running)
|
||||
store.event(ChatEventFrame(sessionId = "a", kind = ChatProtocol.EVENT_STEP, step = net.awan.pipelines.data.protocol.ChatStep(status = ChatProtocol.STEP_ENDED)))
|
||||
assertFalse(store.value.thread("a")!!.running)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun locallyRunningBusyChatStaysWritable() {
|
||||
val store = ChatStore()
|
||||
store.open(session("a", busy = true))
|
||||
store.running("a", true)
|
||||
// Our own turn keeps the session writable even though the server reports it busy.
|
||||
store.draft("a", "next prompt")
|
||||
val thread = store.value.thread("a")!!
|
||||
assertFalse(thread.readOnly)
|
||||
assertTrue(thread.canSend)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun permissionIsStoredAndAnsweredInPlace() {
|
||||
val store = ChatStore()
|
||||
store.open(session("a"))
|
||||
store.permission(ChatPermissionFrame(sessionId = "a", requestId = "r1", action = "edit"))
|
||||
assertEquals("r1", store.value.thread("a")!!.permission!!.requestId)
|
||||
|
||||
store.answerPermission("a", "r1", ChatProtocol.DECISION_ONCE)
|
||||
assertEquals(ChatProtocol.DECISION_ONCE, store.value.thread("a")!!.permissionAnswer)
|
||||
|
||||
// A different request replaces the settled card and drops the old answer.
|
||||
store.permission(ChatPermissionFrame(sessionId = "a", requestId = "r2", action = "bash"))
|
||||
assertEquals("r2", store.value.thread("a")!!.permission!!.requestId)
|
||||
assertEquals("", store.value.thread("a")!!.permissionAnswer)
|
||||
|
||||
// A failed reply reopens the request it answers.
|
||||
store.answerPermission("a", "r2", ChatProtocol.DECISION_REJECT)
|
||||
store.permissionReplyFailed("a", "r2")
|
||||
assertEquals("", store.value.thread("a")!!.permissionAnswer)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun closeRemovesOnlyThatChat() {
|
||||
val store = ChatStore()
|
||||
store.open(session("a"))
|
||||
store.open(session("b"))
|
||||
store.close("a")
|
||||
assertFalse(store.value.open.any { it.sessionId == "a" })
|
||||
assertTrue(store.value.open.any { it.sessionId == "b" })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package net.awan.pipelines.ui.chat
|
||||
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.IntRect
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.LayoutDirection
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* The tool panel's placement: below the chip when it fits, flipped above when it
|
||||
* does not, and always kept inside the window margins. Driven directly against
|
||||
* the provider, so it needs no device or Compose runtime.
|
||||
*/
|
||||
class ToolPanelPositionProviderTest {
|
||||
|
||||
private val provider = ToolPanelPositionProvider(gapPx = 4, marginPx = 8)
|
||||
private val window = IntSize(width = 1000, height = 2000)
|
||||
|
||||
private fun place(anchor: IntRect, content: IntSize): IntOffset =
|
||||
provider.calculatePosition(anchor, window, LayoutDirection.Ltr, content)
|
||||
|
||||
@Test
|
||||
fun placesBelowTheChipWhenItFits() {
|
||||
val anchor = IntRect(left = 40, top = 100, right = 340, bottom = 160)
|
||||
assertEquals(IntOffset(40, 164), place(anchor, IntSize(400, 500)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun flipsAboveWhenThereIsNoRoomBelow() {
|
||||
val anchor = IntRect(left = 40, top = 1800, right = 340, bottom = 1860)
|
||||
// 1860 + 4 + 500 > 2000 - 8, so it goes above: 1800 - 500 - 4 = 1296.
|
||||
assertEquals(IntOffset(40, 1296), place(anchor, IntSize(400, 500)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clampsToTheRightAndTopMargins() {
|
||||
val anchor = IntRect(left = 950, top = 20, right = 990, bottom = 60)
|
||||
// Width 400 cannot start at 950; it is pulled in to the right margin.
|
||||
assertEquals(IntOffset(592, 64), place(anchor, IntSize(400, 500)))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user