diff --git a/apps/albedo/src/albedo/session.gleam b/apps/albedo/src/albedo/session.gleam index 40bfa3363..935e93173 100644 --- a/apps/albedo/src/albedo/session.gleam +++ b/apps/albedo/src/albedo/session.gleam @@ -5356,7 +5356,14 @@ fn opened( case committed, turn.owner(state.activity, run_id) { Ok(#(timestamp, boundary)), run -> { let activity = case run { - Some(run) -> turn.Running(turn.open(run, boundary.upper)) + Some(run) -> { + // Extensions hear the turn begin before its worker may act. + observe( + state, + extension.TurnStarted(turn.isolated_event(submissions)), + ) + turn.Running(turn.open(run, boundary.upper)) + } None -> state.activity } session_state.State(..state, activity: activity) diff --git a/docs/photon.md b/docs/photon.md index aebfc00eb..bb2d5a568 100644 --- a/docs/photon.md +++ b/docs/photon.md @@ -7,7 +7,8 @@ assistant can thread a reply under the text it answers when that makes the conversation clearer, such as when it answers an earlier text. You can close the terminal while the daemon runs. When the session picks up your text for a turn, Albedo asks Photon to mark the conversation as read. You can see Read while the -answer is still in progress. +answer is still in progress. Messages shows the assistant typing while it works +on your text or has an answer left to send. Send a photo on its own or with a caption. Albedo passes the still image to the paired model when it supports image input. On Linux and macOS, Albedo converts diff --git a/e2e/fixtures/photon/server.cjs b/e2e/fixtures/photon/server.cjs index f09b26cb2..9c520801b 100644 --- a/e2e/fixtures/photon/server.cjs +++ b/e2e/fixtures/photon/server.cjs @@ -88,6 +88,14 @@ server.addService(defs.ChatService.service, { record("read", { chatGuid: call.request.chatGuid }); done(null, {}); }, + setTyping(call, done) { + if (!authorized(call) || call.request.chatGuid !== chatGuid) { + return done({ code: grpc.status.PERMISSION_DENIED }); + } + // proto3 leaves a false boolean off the wire. + record("typing", { on: call.request.isTyping === true }); + done(null, {}); + }, createChat(call, done) { if (!authorized(call) || call.request.addresses?.[0] !== recipient) { return done({ diff --git a/e2e/photon_test.py b/e2e/photon_test.py index d31e583dd..b08a397d0 100644 --- a/e2e/photon_test.py +++ b/e2e/photon_test.py @@ -1,4 +1,5 @@ -"""A paired iMessage turn can text back once, even when Photon replays it.""" +"""A paired iMessage turn can text back once, even when Photon replays it, +and the chat shows the assistant typing only while a text's turn runs.""" import base64 import json @@ -11,7 +12,7 @@ import threading import unittest from _imagegen_support import png -from harness import Albedo, Provider, exclusive, python, text, wait_until +from harness import Albedo, Provider, error, exclusive, python, text, wait_until FIXTURE = Path(__file__).parent.resolve() / "fixtures" / "photon" RECIPIENT = "+15550101111" @@ -159,6 +160,10 @@ class PhotonTests(unittest.TestCase): local_turn_started = threading.Event() release_local_turn = threading.Event() release_answer = threading.Event() + release_crash = threading.Event() + earlier_started = threading.Event() + release_earlier = threading.Event() + explicit_mark = [] def prepare(app): self.app = app @@ -176,6 +181,10 @@ class PhotonTests(unittest.TestCase): def respond(request): last = request["input"][-1] if last.get("type") == "function_call_output": + # Typing stops once the explicit reply is sent, while the + # turn that sent it still runs. + if explicit_mark: + self.wait_typing(explicit_mark[0], [True, False]) return text("final after explicit reply") prompt = json.dumps(last) if "send an explicit response" in prompt: @@ -198,9 +207,19 @@ class PhotonTests(unittest.TestCase): if "first managed text" in prompt: if not release_answer.wait(20): raise TimeoutError( - "read receipt missing while the model was answering" + "read receipt or typing missing while the model was answering" ) return text("👋 **first** normal response") + if "answer before a quiet turn" in prompt: + earlier_started.set() + if not release_earlier.wait(20): + raise TimeoutError("the quiet text was never accepted") + return text("earlier answer") + if "fail this turn" in prompt: + return error(400, "provider refused") + if "hold until the crash" in prompt: + release_crash.wait(30) + return text("answer after the crash") if "new text during restart" in prompt: return text("second normal response") return text("answer to local prompt") @@ -221,8 +240,11 @@ class PhotonTests(unittest.TestCase): self.assertEqual( json.load(response), {"session": session, "ready": True} ) + # A new helper tells Photon the current typing state. + self.wait_typing(0, [False]) self.assertFalse(any(c["kind"] == "read" for c in self.calls())) + mark = len(self.calls()) self.app.prompt(session, "hold this local turn").close() self.assertTrue(local_turn_started.wait(10)) try: @@ -233,18 +255,30 @@ class PhotonTests(unittest.TestCase): "Photon did not checkpoint the queued text", ) self.assertFalse(any(c["kind"] == "read" for c in self.calls())) + # A local turn shows no typing, even with a text waiting. + self.assertEqual(self.typing_since(mark), []) finally: release_local_turn.set() try: wait_until( - lambda: any(c["kind"] == "read" for c in self.calls()), + lambda: ( + any(c["kind"] == "read" for c in self.calls()) + and self.typing_since(mark) == [True] + ), 15, - "missing read receipt", + "missing read receipt or typing", ) finally: release_answer.set() self.wait_send("👋 first normal response") self.app.idle(session) + self.wait_typing(mark, [True, False]) + kinds = [ + c["kind"] + for c in self.calls()[mark:] + if c["kind"] in ("typing", "send") + ] + self.assertEqual(kinds, ["typing", "send", "typing"]) self.assertEqual(self.photon_captions(session), ["first managed text"]) @@ -270,11 +304,14 @@ class PhotonTests(unittest.TestCase): self.assertIn(ASSIGNED_NUMBER, imported) self.assertNotIn("fixture-secret", imported) + mark = len(self.calls()) for session_id in (session, other): # A local turn can even resemble a Photon inbox event. self.app.prompt(session_id, "iMessage [first] manual request").close() self.app.idle(session_id) + self.assertEqual(self.typing_since(mark), []) + explicit_mark.append(len(self.calls())) self.publish( {"guid": "echo", "text": "managed outgoing echo", "outgoing": True}, { @@ -287,7 +324,51 @@ class PhotonTests(unittest.TestCase): ) self.wait_send("explicit old response ``a ` *literal*``") self.app.idle(session) + self.assertEqual(self.typing_since(explicit_mark[0]), [True, False]) + + # A turn that fails sends nothing and stops typing. + mark = len(self.calls()) + self.publish({"guid": "failing", "text": "fail this turn"}) + self.wait_typing(mark, [True, False]) + self.app.idle(session) + + # The earlier text's answer still waits when the next text's turn + # starts at once and ends with nothing to send. Typing stays on + # until the earlier answer is sent. + mark = len(self.calls()) + self.publish({"guid": "earlier", "text": "answer before a quiet turn"}) + self.assertTrue(earlier_started.wait(10)) + try: + self.publish({"guid": "quiet", "text": "fail this turn"}) + accepted = len(self.events) + wait_until( + lambda: any(c.get("after") == accepted for c in self.calls()), + 15, + "Photon did not checkpoint the quiet text", + ) + finally: + release_earlier.set() + self.wait_send("earlier answer") + self.app.idle(session) + self.wait_typing(mark, [True, False]) + kinds = [ + c["kind"] + for c in self.calls()[mark:] + if c["kind"] in ("typing", "send") + ] + self.assertEqual(kinds, ["typing", "send", "typing"]) + + # The daemon dies while the chat shows typing. The helper that + # replaces its helper clears what it left. + mark = len(self.calls()) + self.publish({"guid": "crashed", "text": "hold until the crash"}) + self.wait_typing(mark, [True]) + mark = len(self.calls()) + self.app.restart(crash=True, prepare=lambda _: release_crash.set()) + self.wait_typing(mark, [False]) + self.app.idle(session) + mark = len(self.calls()) self.app.restart( prepare=lambda _: self.publish( {"guid": "first", "text": "replayed copy of the first text"}, @@ -296,12 +377,21 @@ class PhotonTests(unittest.TestCase): ) self.wait_send("second normal response") self.app.idle(session) + wait_until( + lambda: ( + self.typing_since(mark)[-1:] == [False] + and True in self.typing_since(mark) + ), + 30, + "typing did not follow the turn after the restart", + ) sends = [c for c in self.calls() if c["kind"] == "send"] self.assertEqual( [c["text"] for c in sends], [ "👋 first normal response", "explicit old response ``a ` *literal*``", + "earlier answer", "second normal response", ], ) @@ -323,6 +413,7 @@ class PhotonTests(unittest.TestCase): {"type": "strikethrough", "start": 9, "length": 3}, ], [], + [], ], ) self.assertEqual( @@ -496,6 +587,17 @@ class PhotonTests(unittest.TestCase): f"no iMessage with text {text!r}", ) + def typing_since(self, mark): + """The typing states Photon was told after the first `mark` calls.""" + return [c["on"] for c in self.calls()[mark:] if c["kind"] == "typing"] + + def wait_typing(self, mark, expected): + wait_until( + lambda: self.typing_since(mark) == expected, + 30, + f"typing after call {mark} was not {expected}", + ) + def wait_reply(self, guid): wait_until( lambda: (self.app.workspace / guid).exists(), diff --git a/extensions/photon/src/albedo_ext_photon.gleam b/extensions/photon/src/albedo_ext_photon.gleam index 47ead7b93..6816988bb 100644 --- a/extensions/photon/src/albedo_ext_photon.gleam +++ b/extensions/photon/src/albedo_ext_photon.gleam @@ -10,11 +10,13 @@ import albedo_sdk/helper_port import albedo_sdk/host import albedo_sdk/storage import albedo_sdk/supervisor_owner +import albedo_sdk/worker import gleam/bool import gleam/dynamic import gleam/dynamic/decode +import gleam/erlang/process import gleam/json -import gleam/option +import gleam/option.{None, Some} import gleam/otp/static_supervisor as supervisor import gleam/otp/supervision import gleam/result @@ -77,9 +79,60 @@ fn start(host: extension.Startup) -> Result(List(extension.Started), String) { ], ), status.plugin(gateway), + extension.StartedOwnedManaged(fn(preparation) { + observe_turns(gateway, preparation) + }), ] } +/// The paired session reports its turns to the manager, which shows the +/// assistant typing. A worker relays them, so the session actor only sends, +/// and a manager that is restarting cannot fail the session. +fn observe_turns( + gateway: manager.Manager, + preparation: extension.Preparation, +) -> Result(option.Option(extension.Owned), String) { + case config.pair() { + Some(pair) if pair.session == preparation.session -> { + use started <- result.map( + worker.start( + preparation.owner, + fn(running) { relay(running, gateway) }, + 5000, + ) + |> result.replace_error("the Photon turn observer did not start"), + ) + let inbox = started.inbox + let observe = fn(session: extension.Session, event) { + case manager.turn(session.id, event) { + Some(turn) -> process.send(inbox, turn) + None -> Nil + } + } + extension.owned( + extension.Managed(..extension.empty(), observe:), + started.adopt, + started.close, + ) + |> Some + } + _ -> Ok(None) + } +} + +fn relay( + running: worker.Running(manager.Message), + gateway: manager.Manager, +) -> Nil { + case worker.receive(running) { + Ok(turn) -> { + manager.observe(gateway, turn) + relay(running, gateway) + } + Error(Nil) -> Nil + } +} + fn record_answer( conn: sqlight.Connection, answer: extension.ExternalAnswer, diff --git a/extensions/photon/src/albedo_ext_photon/ledger.gleam b/extensions/photon/src/albedo_ext_photon/ledger.gleam index 52fd27340..80bcc9ffd 100644 --- a/extensions/photon/src/albedo_ext_photon/ledger.gleam +++ b/extensions/photon/src/albedo_ext_photon/ledger.gleam @@ -220,6 +220,47 @@ fn letter_key(pair: Pair, guid: String) -> String { )) } +/// The received message an inbox letter of this pairing delivers. +pub fn letter_guid(pair: Pair, letter_id: String) -> Option(String) { + case json.parse(letter_id, decode.list(decode.string)) { + Ok(["photon", session, server, recipient, guid]) + if session == pair.session + && server == pair.server + && recipient == pair.recipient + -> Some(guid) + _ -> None + } +} + +/// Whether the running turn's reply reached Photon and whether this pairing +/// has any queued automatic answer, independent of which turn is running. +pub fn reply_state( + db: storage.Storage, + pair: Pair, + answering: Option(String), +) -> Result(#(Bool, Bool), String) { + let guid = case answering { + Some(guid) -> sqlight.text(guid) + None -> sqlight.null() + } + storage.read( + db, + "SELECT + EXISTS (SELECT 1 FROM photon_replies + WHERE session=?1 AND server=?2 AND recipient=?3 AND guid=?4 + AND sent_guid IS NOT NULL), + EXISTS (SELECT 1 FROM photon_outbox + WHERE session=?1 AND server=?2 AND recipient=?3)", + list.append(keys(pair), [guid]), + { + use sent <- decode.field(0, sqlight.decode_bool()) + use queued <- decode.field(1, sqlight.decode_bool()) + decode.success(#(sent, queued)) + }, + ) + |> result.map(fn(rows) { list.first(rows) |> result.unwrap(#(False, False)) }) +} + /// Called inside the turn completion transaction. The inbox row ID is trusted /// turn metadata and must match a message received by this exact pairing. pub fn enqueue_answer( diff --git a/extensions/photon/src/albedo_ext_photon/manager.gleam b/extensions/photon/src/albedo_ext_photon/manager.gleam index a388f4910..f3ee07ad8 100644 --- a/extensions/photon/src/albedo_ext_photon/manager.gleam +++ b/extensions/photon/src/albedo_ext_photon/manager.gleam @@ -30,6 +30,11 @@ pub opaque type Message { Tick Line(generation: Int, line: String) Lookup(pair: Pair, reply: Subject(Option(helper_port.Helper))) + /// A turn of `session` began. `isolated` names the inbox letter it + /// answers when it reads one outside event alone. + Began(session: String, isolated: Option(String)) + /// A turn of `session` ended, completed or not. + Ended(session: String) } type State { @@ -37,10 +42,15 @@ type State { host: extension.Startup, pair: Option(Pair), ready: Bool, - sender: Option(process.Pid), + sender: Option(#(Pair, process.Pid)), self: Subject(Message), generation: Int, helper: Option(helper_port.Helper), + /// The received message whose turn is running, while it has one. + answering: Option(String), + /// What the running helper last told Photon about typing. A new helper + /// has told it nothing. + typing: Option(Bool), ) } @@ -51,7 +61,17 @@ pub fn start( actor.new_with_initialiser(5000, fn(self) { process.send(self, Tick) Ok( - actor.initialised(State(host, None, False, None, self, 0, None)) + actor.initialised(State( + host, + None, + False, + None, + self, + 0, + None, + None, + None, + )) |> actor.returning(self), ) }) @@ -60,6 +80,25 @@ pub fn start( |> actor.start } +/// Project only the events the relay needs, before crossing the mailbox. +pub fn turn(session: String, event: extension.SessionEvent) -> Option(Message) { + case event { + extension.TurnStarted(isolated) -> Some(Began(session, isolated)) + extension.TurnEnded(_) -> Some(Ended(session)) + _ -> None + } +} + +/// Tells the manager about a session's turn. A manager that is not running +/// misses it. +pub fn observe(manager: Manager, message: Message) -> Nil { + let subject = process.named_subject(manager.name) + case process.subject_owner(subject) { + Ok(_) -> process.send(subject, message) + Error(_) -> Nil + } +} + pub fn connected( manager: Manager, pair: Pair, @@ -71,12 +110,20 @@ pub fn connected( }) } +/// Photon does not promise to clear typing when the helper that set it +/// exits, so clear it before closing the helper, unless this helper already did. fn disconnect(state: State) -> State { case state.helper { - Some(port) -> helper_port.close(port) + Some(port) -> { + case state.typing { + Some(False) -> Nil + _ -> act(port, "typing", [#("on", json.bool(False))]) + } + helper_port.close(port) + } None -> Nil } - State(..state, helper: None, ready: False) + State(..state, helper: None, ready: False, typing: None) } fn handle(state: State, message: Message) -> actor.Next(State, Message) { @@ -104,11 +151,11 @@ fn handle(state: State, message: Message) -> actor.Next(State, Message) { } let state = case pair == state.pair { True -> state - False -> State(..disconnect(state), pair:) + False -> State(..disconnect(state), pair:, answering: None) } actor.continue(case pair { None -> state - Some(current) -> reconcile(state, current) + Some(current) -> reconcile(state, current) |> show_typing }) } Line(generation, line) -> { @@ -120,9 +167,70 @@ fn handle(state: State, message: Message) -> actor.Next(State, Message) { } actor.continue(next) } + Began(session, isolated) -> { + let answering = case state.pair { + Some(pair) if pair.session == session -> + option.then(isolated, ledger.letter_guid(pair, _)) + _ -> state.answering + } + actor.continue(show_typing(State(..state, answering:))) + } + Ended(session) -> { + let answering = case state.pair { + Some(pair) if pair.session == session -> None + _ -> state.answering + } + actor.continue(show_typing(State(..state, answering:))) + } } } +/// The chat shows the assistant typing while the turn for a received message +/// runs and no reply to it has reached Photon, and while any automatic answer +/// of the pairing waits in the outbox or is being sent. A later text's turn +/// therefore cannot hide an earlier answer that is still on its way. A helper +/// that has told Photon nothing yet, such as one started after a restart, +/// tells it the current state, clearing one a previous helper left. +fn show_typing(state: State) -> State { + case state.ready, state.helper, state.pair { + True, Some(helper), Some(pair) -> { + let sending_here = case state.sender { + Some(#(owner, pid)) if owner == pair -> process.is_alive(pid) + _ -> False + } + let wanted = + sending_here + || case ledger.reply_state(state.host.storage, pair, state.answering) { + Ok(#(sent, queued)) -> + queued || { option.is_some(state.answering) && !sent } + Error(_) -> False + } + case state.typing == Some(wanted) { + True -> state + False -> { + act(helper, "typing", [#("on", json.bool(wanted))]) + State(..state, typing: Some(wanted)) + } + } + } + _, _, _ -> state + } +} + +/// A chat action is best effort: it takes no reservation and returns no +/// receipt. The helper runs actions in order and logs a failure by name. +fn act( + helper: helper_port.Helper, + action: String, + fields: List(#(String, json.Json)), +) -> Nil { + helper_port.notify(helper, [ + #("op", json.string("action")), + #("action", json.string(action)), + ..fields + ]) +} + fn handle_line( state: State, pair: Pair, @@ -133,7 +241,7 @@ fn handle_line( disconnect(state) }) case json.parse(line, decode.field("type", decode.string, decode.success)) { - Ok("ready") -> State(..state, ready: True) + Ok("ready") -> show_typing(State(..state, ready: True, typing: None)) Ok("event") -> case accept(state, pair, line) { Ok(sequence) -> { @@ -164,11 +272,14 @@ fn reconcile(state: State, pair: Pair) -> State { fn drain(state: State, pair: Pair, helper: helper_port.Helper) -> State { use <- bool.guard(!state.ready, state) case ledger.take_read(state.host.storage, pair) { - Ok(True) -> helper_port.notify(helper, [#("op", json.string("read"))]) + Ok(True) -> act(helper, "read", []) _ -> Nil } use <- bool.guard( - option.map(state.sender, process.is_alive) == Some(True), + case state.sender { + Some(#(_, pid)) -> process.is_alive(pid) + None -> False + }, state, ) case ledger.claim_queued(state.host.storage, pair) { @@ -183,7 +294,7 @@ fn drain(state: State, pair: Pair, helper: helper_port.Helper) -> State { io.println_error("photon: automatic reply: " <> reason) } }) - State(..state, sender: Some(pid)) + State(..state, sender: Some(#(pair, pid))) } _ -> state } diff --git a/extensions/warm/src/albedo_ext_warm/extension.gleam b/extensions/warm/src/albedo_ext_warm/extension.gleam index 6c52e855a..fc644266e 100644 --- a/extensions/warm/src/albedo_ext_warm/extension.gleam +++ b/extensions/warm/src/albedo_ext_warm/extension.gleam @@ -141,6 +141,8 @@ pub fn step(env: Env, warmer: Warmer, message: Message) -> Warmer { } _, _ -> warmer } + // A turn's start changes nothing a ping repeats; its calls report it. + Observed(_, extension.TurnStarted(_)) -> warmer Observed(_, extension.TurnEnded(cancelled: True)) -> warmer // Whether work still waits is asked when the ping would go out, as // after a restore: a job the turn started reports its start once its diff --git a/packages/albedo_sdk/src/albedo_sdk/extension.gleam b/packages/albedo_sdk/src/albedo_sdk/extension.gleam index ffc8ec482..8aa633dd5 100644 --- a/packages/albedo_sdk/src/albedo_sdk/extension.gleam +++ b/packages/albedo_sdk/src/albedo_sdk/extension.gleam @@ -317,6 +317,10 @@ pub type ExternalAnswer { pub type SessionEvent { /// A provider call of a turn succeeded. CallSent(call: SentCall) + /// A turn's inputs are committed and its work begins. `isolated` is the + /// inbox letter the turn answers when it reads one outside event alone, + /// the letter `ExternalAnswer.letter_id` names when it completes. + TurnStarted(isolated: Option(String)) /// A turn ended; a cancelled one was stopped before it finished. TurnEnded(cancelled: Bool) /// A forced compaction rewrote the history the next turn sends. diff --git a/robot-docs/photon.md b/robot-docs/photon.md index 03990c9b2..e040c3bdf 100644 --- a/robot-docs/photon.md +++ b/robot-docs/photon.md @@ -47,8 +47,9 @@ includes the message GUID, so replay can repeat a delivery without starting a second turn. Photon marks the whole chat read. The manager waits for the newest accepted text -to be delivered from the session inbox before requesting a receipt. Receipt -failures are best effort and leave replies and replay independent. +to be delivered from the session inbox before requesting a receipt. The receipt +is a [chat action](#chat-actions-and-typing), so its failures leave replies and +replay independent. For a photo, the helper streams the primary attachment over the authenticated Photon connection after filtering the conversation and sender. A transfer still @@ -63,6 +64,47 @@ reading it back. The primary still keeps its full frame and orientation at up to 2,000 pixels on its longest edge. Failed conversions add a resend instruction alongside the remaining photos and caption. +## Chat actions and typing + +A chat action is a best-effort command on the paired chat: the manager sends +`{"op": "action", "action": name, ...}` and the helper answers nothing. Actions +take no reply reservation and keep no ledger row. The helper runs them one at a +time in the order they arrived, beside replay ACKs and replies, so a later +typing state always wins. A failure is logged with the action's name only, never +with message content, and the helper keeps running. When the daemon closes the +helper's input, the helper waits for queued actions before it closes its Photon +client. `read` and `typing` are the actions. + +The chat shows the assistant typing while a turn answers a received text. The +extension's managed contribution, for the paired session only, starts a worker +that relays the session's `TurnStarted` and `TurnEnded` signals to the manager. +The observer sends only those signals, so provider requests and other events +never enter the relay. `TurnStarted` names the inbox letter of an isolated +outside event, and the manager matches it to a received message of this pairing. +A local or scheduled prompt starts no typing. + +The manager computes the state it wants, checked when a turn starts or ends and +on each 1.5-second tick, and tells the helper only when that differs from what +the helper last sent. Typing is on while either holds: + +- The text's turn runs and its message has no sent reply. An explicit + `photon.reply` stops typing once it reaches Photon unless an automatic answer + is still pending. +- Any automatic answer of the pairing waits in the outbox or is being sent. This + does not depend on the running turn, so a later text's turn that ends quietly + cannot hide an earlier answer still waiting to be sent. + +Otherwise typing is off, including when a turn fails, is cancelled, or ends +quietly with nothing left to send. + +The manager does not assume Photon clears typing when the helper that set it +exits. A new helper has told Photon nothing, so once it reports ready the +manager sends the current state. That clears a state left by a helper that died +with its daemon. Before the manager closes a helper, because the pairing +changed, the session moved or was disabled for Photon, or the route stopped +being direct, it sends typing off unless that helper already did. While no +helper can connect, nothing changes what Photon was last told. + ## Reply in Messages At successful turn completion the session records its visible final answer in diff --git a/robot-docs/plugins.md b/robot-docs/plugins.md index 69b54cf17..358890d5b 100644 --- a/robot-docs/plugins.md +++ b/robot-docs/plugins.md @@ -47,12 +47,14 @@ prepared does not need a `ManagedPlugin`. See collects these contributions in registry order. Managed contributions can observe session events, provide a hook that needs what preparation supplies, and define adoption and close callbacks. Observers run inside the session actor and -must only send and return. Resource close callbacks must be idempotent. -`OwnedManagedPlugin` returns `Result(Option(Owned), String)`. -`extension.owned(contribution, adopt, close)` constructs the opaque value with -both callbacks. `None` retains no resource or contribution. The opaque result -prevents accidentally returning an ordinary contribution with default callbacks. -Resource monitoring remains the allocator's responsibility. +must only send and return. Once a turn's inputs commit, it reports `TurnStarted` +with its isolated letter ID if it has one, and it reports `TurnEnded` however it +ends. Resource close callbacks must be idempotent. `OwnedManagedPlugin` returns +`Result(Option(Owned), String)`. `extension.owned(contribution, adopt, close)` +constructs the opaque value with both callbacks. `None` retains no resource or +contribution. The opaque result prevents accidentally returning an ordinary +contribution with default callbacks. Resource monitoring remains the allocator's +responsibility. ## Record an external answer diff --git a/tools/photon/albedo-photon b/tools/photon/albedo-photon index 3d8eae35c..abab1dcf0 100755 --- a/tools/photon/albedo-photon +++ b/tools/photon/albedo-photon @@ -40,8 +40,10 @@ function connect({ address, token }) { }); } +// The daemon stops reading once it closes the helper's stdin. +let closed = false; function writeFrame(frame) { - process.stdout.write(JSON.stringify(frame) + '\n'); + if (!closed) process.stdout.write(JSON.stringify(frame) + '\n'); } const stop = new AbortController(); let pendingAck; @@ -119,17 +121,37 @@ async function react(client, chatGuid, command) { } } +// Chat actions take no reservation and return no receipt. They run one at a +// time in the order the daemon sent them, so a later typing state always wins, +// while replay ACKs and replies keep flowing. A failure is logged by the +// action's name alone and never stops the helper. +const chatActions = { + read: (client, chat) => client.chats.markRead(chat), + typing: (client, chat, command) => + client.chats.setTyping(chat, command.on === true), +}; +let actions = Promise.resolve(); + +function act(client, chatGuid, command) { + if (!Object.hasOwn(chatActions, command.action)) { + throw new BridgeError('Invalid daemon command'); + } + const action = chatActions[command.action]; + actions = actions + .then(() => action(client, chatGuid, command)) + .catch(() => { + console.error(`Photon chat action failed: ${command.action}`); + }); +} + async function handleCommands(commands, client, chatGuid) { for await (const line of commands) { const command = JSON.parse(line); if (command.op === 'ack' && pendingAck?.sequence === command.sequence) { pendingAck.resolve(); pendingAck = undefined; - } else if (command.op === 'read') { - // Presence is best effort. Keep consuming replay ACKs and reply commands. - void client.chats.markRead(chatGuid).catch(() => { - console.error('Photon could not mark the paired chat as read'); - }); + } else if (command.op === 'action') { + act(client, chatGuid, command); } else if ( command.op === 'react' && Number.isSafeInteger(command.id) && @@ -162,6 +184,10 @@ async function handleCommands(commands, client, chatGuid) { throw new BridgeError('Invalid daemon command'); } } + // The daemon closed the helper, often right after clearing the typing + // indicator. Let queued actions reach Photon before the client closes. + closed = true; + await actions; } async function run(commands) {