diff --git a/README.md b/README.md index 828b10c..cc53d9c 100644 --- a/README.md +++ b/README.md @@ -31,23 +31,31 @@ Any mode: | `pgup`/`pgdn`, `ctrl+u`/`ctrl+d` | scroll the conversation | | `ctrl+c` | quit | -Typing: `enter` sends (queued after the current run if the thread is busy), `shift+enter` or `ctrl+j` adds a newline. +Typing: `enter` sends. While the agent is running, `enter` steers it (the message reaches it mid-run) and `alt+enter` queues the message for after the run, as in T3 Code. With an approval pending, a typed message declines it with your feedback. `shift+enter` or `ctrl+j` adds a newline. Navigation: | Key | Action | | --- | --- | | `j`/`k`, arrows | next / previous thread (scroll, in `attach`) | -| `y` / `Y` / `n` | accept / accept for session / decline the pending approval | -| `e` | expand folded work and long messages | +| `y` / `Y` / `n` | approve / always allow this session / decline the pending approval | +| `1`–`9` | pick an option when the agent asks a question (also in an empty message box) | +| `x` | dismiss the agent's question | +| `e` | expand all folded turns and work groups | +| `o` | load earlier turns | +| `z` | show the Settled and Snoozed sections | | `/` | filter threads by title or project | | `S` | stop the thread | | `g` / `G` | top / bottom of the conversation | | `q` | quit | -The conversation shows your messages and the agent's replies; each run of tool calls and reasoning between them folds into one summary line (`▸ 5 commands · 3 edits`), with the latest step shown while it's running. +The layout follows T3 Code's web app, and much of it uses the web app's own code (vendored from upstream): -Threads are grouped into **Needs you** (waiting on an approval), **Running**, and **Recent**. +- **Sidebar:** the same sections (Pinned, Active, Working, then Snoozed and Settled folded to a count) and the same status words: `Working 2m`, `Waiting`, `Approval`, `Input`, `Request`, `Limited`, `Failed`, `Done`. Threads that need you are bold. +- **Conversation:** built by the web app's timeline logic. Each finished turn's work folds into one line (`Worked for 3m 12s`), your messages are right-aligned, and a running turn shows its live step and `Working for 12s`. +- **Read state:** opening a thread marks it read after a moment, as the web app does. Set `TUI3_NO_VISIT=1` to turn that off. + +Long threads load as a bounded window of recent turns; press `o` for older ones. If the connection drops, tui3 reconnects with backoff and resubscribes. ## How it connects @@ -70,4 +78,4 @@ Type errors after a bump point at the protocol changes to adapt to. ## Not yet supported -Answering agent questions (`user_input` requests), starting new threads, attachments, diffs, and the integrated terminal. Use the T3 Code app for those. +Starting new threads, editing queued messages, plan follow-ups, attachments, diffs, and the integrated terminal. Use the T3 Code app for those. diff --git a/bun.lock b/bun.lock index c7d4d6f..589cce6 100644 --- a/bun.lock +++ b/bun.lock @@ -8,16 +8,24 @@ "@opentui/core": "0.2.7", "@opentui/react": "0.2.7", "effect": "4.0.5", + "mdast-util-directive": "^3.2.0", + "micromark-extension-directive": "^4.0.0", "react": "19", + "remark-parse": "^11.0.0", + "zustand": "5.0.11", }, "devDependencies": { + "@noble/hashes": "1.8.0", "@types/bun": "latest", "@types/react": "^19.3.0", + "jose": "^6.2.14", "typescript": "^5.9.0", }, }, }, "packages": { + "@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], + "@opentui/core": ["@opentui/core@0.2.7", "", { "dependencies": { "bun-ffi-structs": "0.2.2", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0", "strip-ansi": "7.1.2", "yoga-layout": "3.2.1" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.2.7", "@opentui/core-darwin-x64": "0.2.7", "@opentui/core-linux-arm64": "0.2.7", "@opentui/core-linux-x64": "0.2.7", "@opentui/core-win32-arm64": "0.2.7", "@opentui/core-win32-x64": "0.2.7" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-cnN6JcaGC7SeQzobBy/CHzqUAQFtypazuw1CjQBo7WwoOiLMGubt9W5FXeF0zIrSxH2Ed6NLWhPYRg7SD4629Q=="], "@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.2.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-CAy6cL3byz2Xf6gFiJHBpcnsp/2ADEWLLOUokVypOyPLcy8GY3sPzlA4pkAjVGQMYQhDj+Y3+SXz4uTLt4AETg=="], @@ -36,54 +44,184 @@ "@types/bun": ["@types/bun@1.4.4", "", { "dependencies": { "bun-types": "1.4.4" } }, "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ=="], + "@types/debug": ["@types/debug@4.1.13", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="], + + "@types/mdast": ["@types/mdast@4.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA=="], + + "@types/ms": ["@types/ms@2.1.0", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="], + "@types/node": ["@types/node@26.6.6", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="], "@types/react": ["@types/react@19.3.0", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="], + "@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="], + "ansi-regex": ["ansi-regex@6.5.0", "", {}, "sha512-zhvbbbdt1kbw7EJ9OQoxmQcuaNR9P5kTj7e/YdmOSU10aHWbycofJxA6jKfoEy3vlLdctOF9ZHaxLtmSm998wQ=="], + "bail": ["bail@2.0.2", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="], + "bun-ffi-structs": ["bun-ffi-structs@0.2.2", "", { "peerDependencies": { "typescript": "^5" } }, "sha512-N/ZWtyN0piZlrXQT7TO0V+q952orYqkfhXRXM1Hcbb+R3QSiBH4vLnib187Mrs1H7pWIYECAmPeapGYDOMCl+w=="], "bun-types": ["bun-types@1.4.4", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="], + "ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="], + + "character-entities": ["character-entities@2.0.2", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="], + + "character-entities-html4": ["character-entities-html4@2.1.0", "", {}, "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA=="], + + "character-entities-legacy": ["character-entities-legacy@3.0.0", "", {}, "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ=="], + + "character-reference-invalid": ["character-reference-invalid@2.0.1", "", {}, "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw=="], + "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "decode-named-character-reference": ["decode-named-character-reference@1.3.0", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q=="], + + "dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="], + + "devlop": ["devlop@1.1.0", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="], + "diff": ["diff@9.0.0", "", {}, "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw=="], "effect": ["effect@4.0.5", "", {}, "sha512-BY4/28NlpOd99yzmV741xbVGmp+1U7tks4oB7F/Png64bTa5tm5eCA6W0RiXsnuLDDoJpjfVSo4Dnq4BZb/89Q=="], "emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], + "extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="], + "get-east-asian-width": ["get-east-asian-width@1.7.0", "", {}, "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q=="], + "is-alphabetical": ["is-alphabetical@2.0.1", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="], + + "is-alphanumerical": ["is-alphanumerical@2.0.1", "", { "dependencies": { "is-alphabetical": "^2.0.0", "is-decimal": "^2.0.0" } }, "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw=="], + + "is-decimal": ["is-decimal@2.0.1", "", {}, "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A=="], + + "is-hexadecimal": ["is-hexadecimal@2.0.1", "", {}, "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg=="], + + "is-plain-obj": ["is-plain-obj@4.1.0", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="], + + "jose": ["jose@6.2.14", "", {}, "sha512-3JasLuki1NRLQvY4wCoC37KZk4qxoBx2k2aFqLxT84IezqW0bkJKnNtxnZj/Fu1xsQivoc/lytxaRHJoGLjJ1A=="], + + "longest-streak": ["longest-streak@3.1.0", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="], + "marked": ["marked@17.0.1", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-boeBdiS0ghpWcSwoNm/jJBwdpFaMnZWRzjA6SkUMYb40SVaN1x7mmfGKp0jvexGcx+7y2La5zRZsYFZI6Qpypg=="], + "mdast-util-directive": ["mdast-util-directive@3.2.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.2.0", "micromark-util-character": "^2.0.0", "parse-entities": "^4.0.0", "stringify-entities": "^4.0.0" } }, "sha512-Yxq+hH4pBEmtaLIJyMVcNbtBiCIKzdOK3HvDeM+JAqC8XVAT1e5PUYbHBpwFvQLIJuJfO2zCu7aNUXWoyZLmhw=="], + + "mdast-util-from-markdown": ["mdast-util-from-markdown@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A=="], + + "mdast-util-phrasing": ["mdast-util-phrasing@4.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "unist-util-is": "^6.0.0" } }, "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w=="], + + "mdast-util-to-markdown": ["mdast-util-to-markdown@2.2.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "longest-streak": "^3.0.0", "mdast-util-phrasing": "^4.0.0", "mdast-util-to-string": "^4.0.0", "micromark-util-character": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-html-tag-name": "^2.0.0", "unist-util-visit": "^5.0.0", "zwitch": "^2.0.0" } }, "sha512-ThatlCBxG2GE+mljhNSfZPv56d3QrGiRh97jjYgIk80IzS4uU6d7cHAaexCYSAmUCCcOs3grJ07kX3oTGsFUOw=="], + + "mdast-util-to-string": ["mdast-util-to-string@4.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0" } }, "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg=="], + + "micromark": ["micromark@4.0.3", "", { "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-edit-map": "^1.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw=="], + + "micromark-core-commonmark": ["micromark-core-commonmark@2.0.4", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", "micromark-factory-space": "^2.1.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-edit-map": "^1.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.3" } }, "sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w=="], + + "micromark-extension-directive": ["micromark-extension-directive@4.0.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "parse-entities": "^4.0.0" } }, "sha512-/C2nqVmXXmiseSSuCdItCMho7ybwwop6RrrRPk0KbOHW21JKoCldC+8rFOaundDoRBUWBnJJcxeA/Kvi34WQXg=="], + + "micromark-factory-destination": ["micromark-factory-destination@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA=="], + + "micromark-factory-label": ["micromark-factory-label@2.0.1", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg=="], + + "micromark-factory-space": ["micromark-factory-space@2.1.0", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q=="], + + "micromark-factory-title": ["micromark-factory-title@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw=="], + + "micromark-factory-whitespace": ["micromark-factory-whitespace@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ=="], + + "micromark-util-character": ["micromark-util-character@2.1.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q=="], + + "micromark-util-chunked": ["micromark-util-chunked@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA=="], + + "micromark-util-classify-character": ["micromark-util-classify-character@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q=="], + + "micromark-util-combine-extensions": ["micromark-util-combine-extensions@2.0.1", "", { "dependencies": { "micromark-util-chunked": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg=="], + + "micromark-util-decode-numeric-character-reference": ["micromark-util-decode-numeric-character-reference@2.0.2", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw=="], + + "micromark-util-decode-string": ["micromark-util-decode-string@2.0.1", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-symbol": "^2.0.0" } }, "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ=="], + + "micromark-util-edit-map": ["micromark-util-edit-map@1.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q=="], + + "micromark-util-encode": ["micromark-util-encode@2.0.1", "", {}, "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw=="], + + "micromark-util-html-tag-name": ["micromark-util-html-tag-name@2.0.1", "", {}, "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA=="], + + "micromark-util-normalize-identifier": ["micromark-util-normalize-identifier@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q=="], + + "micromark-util-resolve-all": ["micromark-util-resolve-all@2.0.1", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg=="], + + "micromark-util-sanitize-uri": ["micromark-util-sanitize-uri@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-symbol": "^2.0.0" } }, "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ=="], + + "micromark-util-subtokenize": ["micromark-util-subtokenize@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA=="], + + "micromark-util-symbol": ["micromark-util-symbol@2.0.1", "", {}, "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q=="], + + "micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "parse-entities": ["parse-entities@4.0.2", "", { "dependencies": { "@types/unist": "^2.0.0", "character-entities-legacy": "^3.0.0", "character-reference-invalid": "^2.0.0", "decode-named-character-reference": "^1.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0", "is-hexadecimal": "^2.0.0" } }, "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw=="], + "react": ["react@19.3.1", "", {}, "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw=="], "react-devtools-core": ["react-devtools-core@7.0.1", "", { "dependencies": { "shell-quote": "^1.6.1", "ws": "^7" } }, "sha512-C3yNvRHaizlpiASzy7b9vbnBGLrhvdhl1CbdU6EnZgxPNbai60szdLtl+VL76UNOt5bOoVTOz5rNWZxgGt+Gsw=="], "react-reconciler": ["react-reconciler@0.33.0", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.0" } }, "sha512-KetWRytFv1epdpJc3J4G75I4WrplZE5jOL7Yq0p34+OVOKF4Se7WrdIdVC45XsSSmUTlht2FM/fM1FZb1mfQeA=="], + "remark-parse": ["remark-parse@11.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "micromark-util-types": "^2.0.0", "unified": "^11.0.0" } }, "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA=="], + "scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="], "shell-quote": ["shell-quote@1.12.0", "", {}, "sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q=="], "string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], + "stringify-entities": ["stringify-entities@4.0.4", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="], + "strip-ansi": ["strip-ansi@7.1.2", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA=="], + "trough": ["trough@2.2.0", "", {}, "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw=="], + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], "undici-types": ["undici-types@8.12.3", "", {}, "sha512-EXE4ydL3S76dFb27UFjNVZHTyv/TLdATj/KUe29ptdcg6qXL48J2tZ3126E5kICj5jn781OR+XlVH1N6Mz8jbA=="], + "unified": ["unified@11.0.5", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="], + + "unist-util-is": ["unist-util-is@6.0.1", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="], + + "unist-util-stringify-position": ["unist-util-stringify-position@4.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ=="], + + "unist-util-visit": ["unist-util-visit@5.2.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.1.0" } }, "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ=="], + + "unist-util-visit-parents": ["unist-util-visit-parents@6.1.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-vKXxz6O38sKDj1mtx/k2cWvkkFBuYGx6uGrlzBkVeWCRF/F8sdI0j3Wbkz/5rVNRRuVc8UrgRdbCxNhmYXgP3w=="], + + "vfile": ["vfile@6.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="], + + "vfile-message": ["vfile-message@4.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="], + "web-tree-sitter": ["web-tree-sitter@0.25.10", "", { "peerDependencies": { "@types/emscripten": "^1.40.0" }, "optionalPeers": ["@types/emscripten"] }, "sha512-Y09sF44/13XvgVKgO2cNDw5rGk6s26MgoZPXLESvMXeefBf7i6/73eFurre0IsTW6E14Y0ArIzhUMmjoc7xyzA=="], "ws": ["ws@8.22.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g=="], "yoga-layout": ["yoga-layout@3.2.1", "", {}, "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ=="], + "zustand": ["zustand@5.0.11", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-fdZY+dk7zn/vbWNCYmzZULHRrss0jx5pPFiOuMZ/5HJN6Yv3u+1Wswy/4MpZEkEGhtNH+pwxZB8OKgUBPzYAGg=="], + + "zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="], + "@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + "parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="], + "react-devtools-core/ws": ["ws@7.5.13", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA=="], } } diff --git a/package.json b/package.json index 2ef2641..2eb203a 100644 --- a/package.json +++ b/package.json @@ -16,11 +16,17 @@ "@opentui/core": "0.2.7", "@opentui/react": "0.2.7", "effect": "4.0.5", - "react": "19" + "mdast-util-directive": "^3.2.0", + "micromark-extension-directive": "^4.0.0", + "react": "19", + "remark-parse": "^11.0.0", + "zustand": "5.0.11" }, "devDependencies": { + "@noble/hashes": "1.8.0", "@types/bun": "latest", "@types/react": "^19.3.0", + "jose": "^6.2.14", "typescript": "^5.9.0" } } diff --git a/src/bin.ts b/src/bin.ts index 133bd3c..1582ceb 100755 --- a/src/bin.ts +++ b/src/bin.ts @@ -2,7 +2,7 @@ import type { OrchestrationV2ShellSnapshot } from "@t3tools/contracts"; import { T3Session } from "./client/session.ts"; -import { findThread, lastActivity, relativeTime, shortId, threadRows } from "./model/threads.ts"; +import { findThread, lastActivity, relativeTime, rowTime, shortId, statusLabel, threadRows } from "./model/threads.ts"; const USAGE = `tui3: a terminal client for T3 Code @@ -62,13 +62,13 @@ async function connectedSession(): Promise<{ session: T3Session; snapshot: Orche async function list(json: boolean) { const { session, snapshot } = await connectedSession(); - const rows = threadRows(snapshot, { recentLimit: 40 }); + const rows = threadRows(snapshot, { settledLimit: 20 }); if (json) { - console.log(JSON.stringify(rows.map((row) => ({ id: row.thread.id, title: row.thread.title, project: row.projectName, group: row.group, status: row.thread.status, updatedAt: new Date(lastActivity(row.thread)).toISOString() })), null, 2)); + console.log(JSON.stringify(rows.map((row) => ({ id: row.thread.id, title: row.thread.title, project: row.projectName, section: row.section, status: row.status, unread: row.unread, updatedAt: new Date(lastActivity(row.thread)).toISOString() })), null, 2)); } else { for (const row of rows) { - const mark = row.group === "needs-you" ? "!" : row.group === "running" ? "~" : " "; - console.log(`${mark} ${shortId(row.thread.id)} ${relativeTime(lastActivity(row.thread)).padStart(4)} ${row.projectName.padEnd(20).slice(0, 20)} ${row.thread.title}`); + const status = statusLabel(row)?.text ?? relativeTime(rowTime(row.thread)); + console.log(`${shortId(row.thread.id)} ${row.section.padEnd(8)} ${status.padEnd(12)} ${row.projectName.padEnd(20).slice(0, 20)} ${row.thread.title}`); } } await session.stop(); diff --git a/src/client/session.ts b/src/client/session.ts index 90f5fb3..9557b41 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -14,6 +14,7 @@ import { } from "@t3tools/contracts"; import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection"; import { mergeOlderHistoryIntoProjection } from "@t3tools/client-runtime/state/thread-history-merge"; +import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; import { appendFileSync } from "node:fs"; @@ -189,9 +190,12 @@ export class T3Session { } } - sendMessage(threadId: ThreadId, text: string, mode: "queue" | "steer" = "queue"): Promise { + /** + * Sends a message the way the web composer does: "auto" when idle, otherwise + * "steer" (into the active run) or "queue" (after it). See resolveComposerDispatchMode. + */ + sendMessage(threadId: ThreadId, text: string, mode: ComposerDispatchMode = "auto"): Promise { const commandId = newCommandId(); - const running = this.threads.get(threadId)?.state.projection?.runs.findLast((run) => isActiveRun(run.status)); return this.dispatch({ type: "message.dispatch", commandId, @@ -199,17 +203,29 @@ export class T3Session { messageId: MessageId.make(commandId), text, attachments: [], - dispatchMode: - mode === "steer" && running - ? { type: "steer_active", targetRunId: running.id } - : { type: "queue_after_active" }, + ...(mode === "queue" ? { dispatchMode: { type: "queue_after_active" } } : { dispatchMode: { type: "start_immediately" }, deliveryIntent: mode }), createdBy: "user", creationSource: "web", }); } - respond(threadId: ThreadId, requestId: RuntimeRequestId, decision: ProviderApprovalDecision): Promise { - return this.dispatch({ type: "runtime-request.respond", commandId: newCommandId(), threadId, requestId, decision }); + respond(threadId: ThreadId, requestId: RuntimeRequestId, decision: ProviderApprovalDecision, feedback?: string): Promise { + return this.dispatch({ type: "runtime-request.respond", commandId: newCommandId(), threadId, requestId, decision, ...(feedback ? { feedback } : {}) }); + } + + /** Answers a user-input request; answers map question id to an option value, typed text, or several values. */ + answer(threadId: ThreadId, requestId: RuntimeRequestId, answers: Record): Promise { + return this.dispatch({ type: "runtime-request.respond", commandId: newCommandId(), threadId, requestId, answers: answers as Record }); + } + + dismissQuestion(threadId: ThreadId, requestId: RuntimeRequestId): Promise { + return this.dispatch({ type: "thread.user-input.dismiss", commandId: newCommandId(), threadId, requestId }); + } + + /** Moves the thread's read watermark, as opening it in the web app does. TUI3_NO_VISIT=1 peeks without it. */ + visit(threadId: ThreadId): Promise { + if (process.env.TUI3_NO_VISIT === "1") return Promise.resolve(); + return this.dispatch({ type: "thread.visit", commandId: newCommandId(), threadId, visitedAt: new Date().toISOString(), opened: true }); } /** Stops whatever the thread is running, the way the GUI's stop button does. */ @@ -352,8 +368,6 @@ export class T3Session { } } -const isActiveRun = (status: string) => status === "preparing" || status === "starting" || status === "running" || status === "waiting"; - const isSocketFailure = (message: string) => /Socket(Close|Open|Generic)?Error|socket/i.test(message); const newCommandId = () => CommandId.make(crypto.randomUUID()); diff --git a/src/model/threads.ts b/src/model/threads.ts index bc0e8a7..55cb6d9 100644 --- a/src/model/threads.ts +++ b/src/model/threads.ts @@ -1,66 +1,142 @@ -import type { OrchestrationProjectShell, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ProjectId } from "@t3tools/contracts"; +import type { EnvironmentId, OrchestrationProjectShell, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ProjectId } from "@t3tools/contracts"; +import { formatWorkingDurationLabel, presentThreadShell, resolveThreadWorkingStartedAt, type EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; +import { isThreadWorking, sortInboxThreadsByReturn, sortWorkingThreadsBySend } from "@t3tools/client-runtime/state/thread-inbox"; +import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; +import { sortPinnedThreadsByOrderKey, sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort"; import * as DateTime from "effect/DateTime"; -export type ThreadGroup = "needs-you" | "running" | "recent"; +/** The web sidebar's sections, in its order. Active has no header unless others show. */ +export type Section = "pinned" | "active" | "working" | "snoozed" | "settled"; + +/** The web sidebar's row status (resolveSidebarThreadStatus). */ +export type ThreadStatus = "approval" | "input" | "request" | "waiting" | "working" | "limited" | "failed" | "ready"; export interface ThreadRow { readonly thread: OrchestrationV2ThreadShell; - readonly group: ThreadGroup; + readonly shell: EnvironmentThreadShell; + readonly section: Section; + readonly status: ThreadStatus; + /** Finished since you last opened it. */ + readonly unread: boolean; readonly projectName: string; } -export const GROUP_LABELS: Record = { - "needs-you": "Needs you", - running: "Running", - recent: "Recent", +export const SECTION_LABELS: Record = { + pinned: "Pinned", + active: "Active", + working: "Working", + snoozed: "Snoozed", + settled: "Settled", }; -const ACTIVE_STATUSES = new Set(["preparing", "starting", "running", "waiting"]); +export const SECTION_ORDER: readonly Section[] = ["pinned", "active", "working", "snoozed", "settled"]; -export function needsUser(thread: OrchestrationV2ThreadShell): boolean { - return thread.pendingRuntimeRequest !== null && thread.pendingRuntimeRequest.blocking !== false; +/** Only one server, so any constant id works for presentThreadShell. */ +const LOCAL_ENVIRONMENT = "local" as EnvironmentId; + +export function resolveStatus(shell: EnvironmentThreadShell): ThreadStatus { + if (shell.hasPendingApprovals || shell.pendingSubagentRequest === "approval") return "approval"; + if (shell.hasPendingUserInput || shell.pendingSubagentRequest === "user_input") return "input"; + if ((shell.pendingGuestMessageCount ?? 0) > 0) return "request"; + const runtime = shell.runtime; + if (runtime?.status === "running" && shell.blockedOnThreadWait) return "waiting"; + if (runtime && ["preparing", "queued", "starting", "running", "waiting"].includes(runtime.status)) return "working"; + if (runtime?.status === "idle") return "waiting"; + if (runtime?.status === "failed") return runtime.lastErrorClass === "usage_limit" ? "limited" : "failed"; + return "ready"; } -export function isRunning(thread: OrchestrationV2ThreadShell): boolean { - return thread.activeRunId !== null || ACTIVE_STATUSES.has(thread.status); +export function hasUnseenCompletion(shell: EnvironmentThreadShell): boolean { + const completedAt = Date.parse(shell.latestRun?.completedAt ?? ""); + if (Number.isNaN(completedAt) || !shell.lastVisitedAt) return false; + const visitedAt = Date.parse(shell.lastVisitedAt); + return Number.isNaN(visitedAt) || completedAt > visitedAt; } -export function groupOf(thread: OrchestrationV2ThreadShell): ThreadGroup { - if (needsUser(thread)) return "needs-you"; - if (isRunning(thread)) return "running"; - return "recent"; +/** Whether the thread is waiting on you: the rows the web sidebar shows in bold. */ +export function needsAttention(row: Pick): boolean { + return row.status === "approval" || row.status === "input" || row.status === "request" || row.status === "failed" || row.status === "limited" || row.unread; +} + +/** The sidebar's top-right status word, or null to show the time instead. */ +export function statusLabel(row: ThreadRow, now = Date.now()): { readonly text: string; readonly tone: StatusTone } | null { + switch (row.status) { + case "working": { + const label = row.shell.goal?.status === "active" ? "Goal" : "Working"; + const since = resolveThreadWorkingStartedAt(row.shell); + return { text: since ? `${label} ${formatWorkingDurationLabel(now - Date.parse(since))}` : label, tone: "info" }; + } + case "waiting": + return { text: "Waiting", tone: "muted" }; + case "approval": + return { text: "Approval", tone: "warn" }; + case "input": + return { text: "Input", tone: "input" }; + case "request": + return { text: "Request", tone: "input" }; + case "limited": + return { text: "Limited", tone: "warn" }; + case "failed": + return { text: "Failed", tone: "bad" }; + case "ready": + return row.unread ? { text: "Done", tone: "good" } : null; + } +} + +export type StatusTone = "info" | "muted" | "warn" | "input" | "bad" | "good"; + +/** Threads in the web sidebar's sections and order. Subagent threads stay under their parent, so they're left out. */ +export function threadRows( + snapshot: OrchestrationV2ShellSnapshot | null, + options: { readonly query?: string; readonly settledLimit?: number; readonly now?: string } = {}, +): ThreadRow[] { + if (!snapshot) return []; + const projects = new Map(snapshot.projects.map((project) => [project.id, project])); + const query = options.query?.trim().toLowerCase(); + const now = options.now ?? new Date().toISOString(); + const bySection: Record = { pinned: [], active: [], working: [], snoozed: [], settled: [] }; + for (const thread of snapshot.threads) { + if (thread.archivedAt !== null || thread.deletedAt !== null || thread.lineage.relationshipToParent === "subagent") continue; + const projectName = projectLabel(projects.get(thread.projectId)); + if (query && !thread.title.toLowerCase().includes(query) && !projectName.toLowerCase().includes(query)) continue; + const shell = presentThreadShell(LOCAL_ENVIRONMENT, thread); + const section: Section = effectiveSnoozed(shell, { now }) + ? "snoozed" + : shell.settledOverride === "settled" + ? "settled" + : shell.pinnedAt != null + ? "pinned" + : isThreadWorking(shell) + ? "working" + : "active"; + bySection[section].push(shell); + } + const sorted: Record = { + pinned: sortPinnedThreadsByOrderKey(bySection.pinned), + active: sortInboxThreadsByReturn(bySection.active), + working: sortWorkingThreadsBySend(bySection.working), + snoozed: bySection.snoozed.toSorted((a, b) => Date.parse(a.snoozedUntil ?? "") - Date.parse(b.snoozedUntil ?? "")), + settled: sortSettledThreads(bySection.settled).slice(0, options.settledLimit ?? 30), + }; + return SECTION_ORDER.flatMap((section) => + sorted[section].map((shell) => ({ + thread: shell.source as OrchestrationV2ThreadShell, + shell, + section, + status: resolveStatus(shell), + unread: hasUnseenCompletion(shell), + projectName: projectLabel(projects.get(shell.projectId)), + })), + ); } export function lastActivity(thread: OrchestrationV2ThreadShell): number { return DateTime.toEpochMillis(thread.updatedAt); } -const millis = (value: DateTime.Utc | null | undefined) => (value ? DateTime.toEpochMillis(value) : 0); - -/** - * Sort key within a group. Active threads update every second while they - * stream, so they sort by something that holds still: when they started - * waiting on you, or when their run began. - */ -export function sortKey(thread: OrchestrationV2ThreadShell, group: ThreadGroup): number { - if (group === "needs-you") return millis(thread.pendingRuntimeRequest?.createdAt) || millis(thread.createdAt); - if (group === "running") return millis(thread.latestRunStartedAt) || millis(thread.latestRunRequestedAt) || millis(thread.createdAt); - return lastActivity(thread); -} - -/** Threads in display order: the ones waiting on you, then running, then the most recent. */ -export function threadRows(snapshot: OrchestrationV2ShellSnapshot | null, options: { readonly recentLimit?: number; readonly query?: string } = {}): ThreadRow[] { - if (!snapshot) return []; - const projects = new Map(snapshot.projects.map((project) => [project.id, project])); - const query = options.query?.trim().toLowerCase(); - const order: ThreadGroup[] = ["needs-you", "running", "recent"]; - const rows = snapshot.threads - .map((thread) => ({ thread, group: groupOf(thread), projectName: projectLabel(projects.get(thread.projectId)) })) - .filter((row) => !query || row.thread.title.toLowerCase().includes(query) || row.projectName.toLowerCase().includes(query)) - .sort((a, b) => order.indexOf(a.group) - order.indexOf(b.group) || sortKey(b.thread, b.group) - sortKey(a.thread, a.group) || a.thread.id.localeCompare(b.thread.id)); - const limit = options.recentLimit ?? 60; - let recent = 0; - return rows.filter((row) => row.group !== "recent" || recent++ < limit); +/** The time the sidebar shows: your latest message, else the last update. */ +export function rowTime(thread: OrchestrationV2ThreadShell): number { + return thread.latestUserMessageAt ? DateTime.toEpochMillis(thread.latestUserMessageAt) : lastActivity(thread); } export function projectLabel(project: OrchestrationProjectShell | undefined): string { @@ -84,8 +160,10 @@ export function shortId(id: string): string { return id.slice(-8); } +/** Compact relative time, like the sidebar's: "now", "45s", "3m", "2h", "4d". */ export function relativeTime(ms: number, now = Date.now()): string { const seconds = Math.max(0, Math.round((now - ms) / 1000)); + if (seconds < 5) return "now"; if (seconds < 60) return `${seconds}s`; const minutes = Math.round(seconds / 60); if (minutes < 60) return `${minutes}m`; diff --git a/src/model/timeline.ts b/src/model/timeline.ts new file mode 100644 index 0000000..0377ead --- /dev/null +++ b/src/model/timeline.ts @@ -0,0 +1,102 @@ +import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import { + deriveRunlessWorkStartedAt, + deriveThreadActivityRun, + deriveThreadStructureRuntime, +} from "@t3tools/client-runtime/state/thread-execution"; +import { derivePendingThreadRequests, type PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests"; + +// The web app's own timeline derivation: tui3 shows the same rows, folds and labels. +import { + computeStableMessagesTimelineRows, + deriveMessagesTimelineRowsWithState, + type MessagesTimelineRow, + type MessagesTimelineRowsInput, + type StableMessagesTimelineRowsState, +} from "../../vendor/t3code/apps/web/src/components/chat/MessagesTimeline.logic.ts"; +import { + deriveActiveWorkStartedAt, + derivePhase, + deriveTimelineEntriesFromVisibleTurnItemsWithState, + type TimelineEntriesProjection, +} from "../../vendor/t3code/apps/web/src/session-logic.ts"; + +export type { MessagesTimelineRow } from "../../vendor/t3code/apps/web/src/components/chat/MessagesTimeline.logic.ts"; +export type { WorkLogEntry } from "../../vendor/t3code/apps/web/src/session-logic.ts"; +export { liveWorkEntryLabel, workEntryDisplayLabel } from "../../vendor/t3code/apps/web/src/components/chat/MessagesTimeline.logic.ts"; + +export interface Timeline { + readonly rows: readonly MessagesTimelineRow[]; + readonly pending: PendingThreadRequests; + readonly isWorking: boolean; + /** When the current run started working, for "Working for 12s". */ + readonly workStartedAt: string | null; + /** Carried into the next build so unchanged rows keep their identity. */ + readonly cache: TimelineCache; +} + +interface TimelineCache { + readonly entries: TimelineEntriesProjection; + readonly rows: { readonly input: MessagesTimelineRowsInput; readonly rows: MessagesTimelineRow[] }; + readonly stable: StableMessagesTimelineRowsState; + readonly expandAll: boolean; +} + +/** Answers yes for every id: "expand everything" without knowing the group ids up front. */ +class EverySet extends Set { + override has(): boolean { + return true; + } +} +const EVERYTHING = new EverySet(); +const NOTHING = new Set(); + +export function buildTimeline( + projection: OrchestrationV2ThreadProjection, + options: { readonly expandAll: boolean }, + previous: Timeline | null, +): Timeline { + const cache = previous?.cache.expandAll === options.expandAll ? previous.cache : null; + const entries = deriveTimelineEntriesFromVisibleTurnItemsWithState( + { + visibleTurnItems: projection.visibleTurnItems, + optimisticMessages: [], + attempts: projection.attempts, + nodes: projection.nodes, + plans: projection.plans, + }, + cache?.entries ?? null, + ); + const runtime = deriveThreadStructureRuntime(projection); + const latestRun = deriveThreadActivityRun(projection); + const runlessStartedAt = deriveRunlessWorkStartedAt(projection); + const isWorking = derivePhase(runtime) === "running" || runlessStartedAt !== null; + const workStartedAt = deriveActiveWorkStartedAt(latestRun, runtime, null) ?? runlessStartedAt; + const pending = derivePendingThreadRequests(projection); + const expanded = options.expandAll ? EVERYTHING : NOTHING; + const rows = deriveMessagesTimelineRowsWithState( + { + timelineEntries: entries.entries, + pendingApprovalRequestIds: new Set(pending.approvals.map((approval) => approval.requestId)), + latestRun, + runningRunId: runtime?.activeRunId ?? null, + expandedRunIds: expanded, + expandedAttemptIds: expanded, + expandedWorkGroupIds: expanded, + isWorking, + runlessWorkActive: runlessStartedAt !== null, + activeTurnStartedAt: workStartedAt, + turnDiffSummaries: [], + supportsConversationRollback: false, + }, + cache?.rows ?? null, + ); + const stable = computeStableMessagesTimelineRows(rows.rows, cache?.stable ?? { byId: new Map(), result: [] }); + return { + rows: stable.result, + pending, + isWorking, + workStartedAt, + cache: { entries, rows, stable, expandAll: options.expandAll }, + }; +} diff --git a/src/model/transcript.ts b/src/model/transcript.ts index e31f6b6..2ae5976 100644 --- a/src/model/transcript.ts +++ b/src/model/transcript.ts @@ -1,6 +1,6 @@ -import type { OrchestrationV2ThreadProjection, OrchestrationV2TurnItem, RuntimeRequestId } from "@t3tools/contracts"; +import type { OrchestrationV2TurnItem, RuntimeRequestId } from "@t3tools/contracts"; -/** One rendered row of the transcript. Markdown blocks get the markdown renderer; the rest are plain lines. */ +/** A turn item as one line or card: the fallback for timeline event rows the web app renders specially. */ export type Block = | { readonly kind: "user"; readonly id: string; readonly text: string } | { readonly kind: "assistant"; readonly id: string; readonly markdown: string; readonly streaming: boolean } @@ -12,110 +12,8 @@ export type Block = export type Tone = "normal" | "muted" | "good" | "bad" | "warn"; -/** Tool calls, reasoning and minor notices: the agent's working, as opposed to what it says. */ -export type Step = Extract; - -/** What the conversation view renders: messages stand alone, runs of work fold into one segment. */ -export type Segment = - | Extract - | { readonly kind: "work"; readonly id: string; readonly steps: readonly Step[]; readonly active: boolean } - | { readonly kind: "alert"; readonly id: string; readonly text: string; readonly tone: Tone }; - -export interface Transcript { - readonly segments: readonly Segment[]; - /** Turn items left out because only the tail is shown. */ - readonly hiddenCount: number; -} - const OUTPUT_TAIL_LINES = 3; -/** Blocks keyed by turn item object: the projection reducer keeps unchanged items identical. */ -const blockCache = new WeakMap(); - -function cachedBlock(item: OrchestrationV2TurnItem, pending: ReadonlySet): Block | null { - // Approval and question blocks depend on request state, not just the item. - if (item.type === "approval_request" || item.type === "user_input_request") return blockFor(item, pending); - let block = blockCache.get(item); - if (block === undefined) { - block = blockFor(item, pending); - blockCache.set(item, block); - } - return block; -} - -export function buildTranscript( - projection: OrchestrationV2ThreadProjection, - options: { readonly tail?: number; readonly running?: boolean; readonly previous?: Transcript | null } = {}, -): Transcript { - const pending = new Set(projection.runtimeRequests.filter((request) => request.status === "pending").map((request) => request.id as string)); - const items = projection.visibleTurnItems; - const tail = options.tail ?? 200; - const start = Math.max(0, items.length - tail); - const segments: Segment[] = []; - let work: Step[] | null = null; - const flushWork = () => { - if (work && work.length > 0) segments.push({ kind: "work", id: `work-${work[0]!.id}`, steps: work, active: false }); - work = null; - }; - for (let index = start; index < items.length; index++) { - const block = cachedBlock(items[index]!.item, pending); - if (!block) continue; - if (block.kind === "tool" || block.kind === "reasoning" || (block.kind === "notice" && block.tone !== "bad" && block.tone !== "warn")) { - (work ??= []).push(block); - continue; - } - flushWork(); - segments.push(block.kind === "notice" ? { kind: "alert", id: block.id, text: block.text, tone: block.tone } : block); - } - flushWork(); - const last = segments.at(-1); - if (options.running && last?.kind === "work") segments[segments.length - 1] = { ...last, active: true }; - return { segments: reuseUnchanged(segments, options.previous ?? null), hiddenCount: start }; -} - -/** Keeps the previous segment object when nothing in it changed, so memoized views skip it. */ -function reuseUnchanged(segments: Segment[], previous: Transcript | null): Segment[] { - if (!previous) return segments; - const byId = new Map(previous.segments.map((segment) => [segment.id, segment])); - return segments.map((segment) => { - const old = byId.get(segment.id); - return old && sameSegment(old, segment) ? old : segment; - }); -} - -function sameSegment(a: Segment, b: Segment): boolean { - if (a === b) return true; - if (a.kind !== b.kind) return false; - if (a.kind === "work" && b.kind === "work") { - return a.active === b.active && a.steps.length === b.steps.length && a.steps.every((step, index) => step === b.steps[index]); - } - return shallowEqual(a as unknown as Record, b as unknown as Record); -} - -function shallowEqual(a: Record, b: Record): boolean { - const keys = Object.keys(a); - return keys.length === Object.keys(b).length && keys.every((key) => Object.is(a[key], b[key]) || (Array.isArray(a[key]) && Array.isArray(b[key]) && shallowEqualArray(a[key] as unknown[], b[key] as unknown[]))); -} - -function shallowEqualArray(a: unknown[], b: unknown[]): boolean { - return a.length === b.length && a.every((value, index) => Object.is(value, b[index])); -} - -/** One line describing a folded run of work, e.g. "5 commands · 3 edits · 2 searches". */ -export function summarizeWork(steps: readonly Step[]): string { - const counts = new Map(); - const bump = (label: string) => counts.set(label, (counts.get(label) ?? 0) + 1); - for (const step of steps) { - if (step.kind === "reasoning") continue; - if (step.kind === "notice") bump("update"); - else bump(STEP_LABELS[step.icon] ?? "tool call"); - } - const parts = [...counts].sort((a, b) => b[1] - a[1]).map(([label, count]) => `${count} ${count === 1 ? label : `${label}s`}`); - return parts.length > 0 ? parts.join(" · ") : "thinking"; -} - -const STEP_LABELS: Record = { $: "command", "✎": "edit", "⌕": "search", "⚙": "tool call", "↳": "subagent", "☐": "plan update" }; - export function blockFor(item: OrchestrationV2TurnItem, pending: ReadonlySet): Block | null { const id = item.id; switch (item.type) { diff --git a/src/mux/tmux.ts b/src/mux/tmux.ts index b95e732..d64260d 100644 --- a/src/mux/tmux.ts +++ b/src/mux/tmux.ts @@ -1,6 +1,6 @@ import type { OrchestrationV2ShellSnapshot } from "@t3tools/contracts"; -import { threadRows, type ThreadRow } from "../model/threads.ts"; +import { needsAttention, threadRows, type ThreadRow } from "../model/threads.ts"; /** Window option that ties a tmux window to the thread it attaches to. */ const THREAD_OPTION = "@tui3_thread"; @@ -22,7 +22,7 @@ async function tmux(args: readonly string[], allowFailure = false): Promise parts.map((part) => `'${part.replaceAll("'", `'\\''`)}'`).join(" "); export function windowName(row: ThreadRow): string { - const mark = row.group === "needs-you" ? "● " : row.group === "running" ? "" : "✓ "; + const mark = needsAttention(row) && row.status !== "ready" ? "● " : row.status === "working" || row.status === "waiting" ? "" : "✓ "; const title = (row.thread.title || "thread").replace(/\s+/g, " "); return mark + (title.length > TITLE_WIDTH ? `${title.slice(0, TITLE_WIDTH - 1)}…` : title); } @@ -42,8 +42,10 @@ export async function syncTmux(snapshot: OrchestrationV2ShellSnapshot, options: const [windowId, threadId] = line.split("\t"); if (windowId && threadId) windows.set(threadId, windowId); } - const rows = threadRows(snapshot, { recentLimit: 0 }); - const byId = new Map(threadRows(snapshot, { recentLimit: Number.MAX_SAFE_INTEGER }).map((row) => [row.thread.id as string, row])); + const all = threadRows(snapshot, { settledLimit: 0 }); + // A window per thread that's working or waiting on you. + const rows = all.filter((row) => row.section === "working" || row.status === "approval" || row.status === "input" || row.status === "request"); + const byId = new Map(all.map((row) => [row.thread.id as string, row])); let opened = 0; for (const row of rows) { if (windows.has(row.thread.id)) continue; diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 20d189f..f0f2338 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -1,11 +1,20 @@ import type { KeyEvent, ScrollBoxRenderable, TextareaRenderable } from "@opentui/core"; import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/react"; +import { resolveComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; +import { + buildPendingUserInputAnswers, + resolvePendingUserInputAnswer, + setPendingUserInputCustomAnswer, + togglePendingUserInputOptionSelection, + type PendingUserInputDraftAnswer, +} from "@t3tools/client-runtime/state/pending-user-input"; import type { ProviderApprovalDecision, ThreadId } from "@t3tools/contracts"; import { useEffect, useMemo, useRef, useState } from "react"; import type { ShellState, T3Session, ThreadState } from "../client/session.ts"; -import { buildTranscript, type Transcript } from "../model/transcript.ts"; -import { isRunning, lastActivity, needsUser, relativeTime, threadRows } from "../model/threads.ts"; +import { buildTimeline, type Timeline } from "../model/timeline.ts"; +import { threadRows, type Section } from "../model/threads.ts"; +import { QuestionPanel } from "./QuestionPanel.tsx"; import { colors } from "./theme.ts"; import { ThreadList } from "./ThreadList.tsx"; import { ThreadView } from "./ThreadView.tsx"; @@ -15,15 +24,30 @@ type Mode = "input" | "nav" | "filter"; /** Holding j/k skims past threads; only subscribe to one you stop on. */ const SUBSCRIBE_DELAY_MS = 120; +/** Opening a thread marks it read once you've stayed this long, as in the web app. */ +const VISIT_DELAY_MS = 1_500; const MAX_COMPOSER_LINES = 6; +/** Sections folded to a count unless you filter or press z, like the web sidebar's. */ +const FOLDED_SECTIONS: readonly Section[] = ["snoozed", "settled"]; const COMPOSER_KEYS = [ { name: "return", action: "submit" }, { name: "return", shift: true, action: "newline" }, - { name: "return", meta: true, action: "newline" }, { name: "j", ctrl: true, action: "newline" }, ] as const; +const RUNTIME_MODE_LABELS: Record = { + "approval-required": "Supervised", + "auto-accept-edits": "Auto-accept edits", + auto: "Auto", + "full-access": "Full access", +}; + +interface QuestionDraft { + readonly index: number; + readonly answers: Record; +} + export function App(props: { readonly session: T3Session; readonly attachThreadId?: ThreadId }) { const { session, attachThreadId } = props; const renderer = useRenderer(); @@ -32,20 +56,36 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI const [selectedId, setSelectedId] = useState(attachThreadId); const [mode, setMode] = useState(attachThreadId ? "input" : "nav"); const [filter, setFilter] = useState(""); - const [expandWork, setExpandWork] = useState(false); + const [showFolded, setShowFolded] = useState(false); + const [expandAll, setExpandAll] = useState(false); const [flash, setFlash] = useState<{ text: string; bad?: boolean } | null>(null); const [composerLines, setComposerLines] = useState(1); + const [composerEmpty, setComposerEmpty] = useState(true); + const [questionDrafts, setQuestionDrafts] = useState>(new Map()); + const [now, setNow] = useState(Date.now()); const scrollRef = useRef(null); const composerRef = useRef(null); const drafts = useRef(new Map()); useEffect(() => session.onShell(setShell), [session]); + // Drives "Working for 12s" and the sidebar's durations. + useEffect(() => { + const timer = setInterval(() => setNow(Date.now()), 1_000); + return () => clearInterval(timer); + }, []); - const rows = useMemo(() => threadRows(shell.snapshot, { query: filter }), [shell.snapshot, filter]); + const allRows = useMemo(() => threadRows(shell.snapshot, { query: filter }), [shell.snapshot, filter]); + const unfold = showFolded || filter.trim() !== ""; + const rows = useMemo(() => (unfold ? allRows : allRows.filter((row) => !FOLDED_SECTIONS.includes(row.section))), [allRows, unfold]); + const collapsed = useMemo( + () => new Map(unfold ? [] : FOLDED_SECTIONS.map((section) => [section, allRows.filter((row) => row.section === section).length] as const)), + [allRows, unfold], + ); // Selection is a thread id, not an index, so the list can reorder underneath it. const selectedIndex = Math.max(0, rows.findIndex((row) => row.thread.id === selectedId)); const threadId = attachThreadId ?? rows[selectedIndex]?.thread.id; - const threadShell = shell.snapshot?.threads.find((thread) => thread.id === threadId); + const threadRow = allRows.find((row) => row.thread.id === threadId); + const threadShell = threadRow?.thread ?? shell.snapshot?.threads.find((thread) => thread.id === threadId); // Pin the initial selection to a thread, or it would follow whatever sorts first. useEffect(() => { if (selectedId === undefined && rows[0]) setSelectedId(rows[0].thread.id); @@ -65,44 +105,107 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI const [thread, setThread] = useState(null); useEffect(() => { setThread(null); - if (!watchedId || !shell.serverUrl) return; + if (!watchedId || shell.status.type !== "live") return; return session.watchThread(watchedId, setThread); - }, [session, watchedId, shell.serverUrl]); + }, [session, watchedId, shell.status.type]); - const running = threadShell ? isRunning(threadShell) && !needsUser(threadShell) : false; - const previousTranscript = useRef<{ id: string; transcript: Transcript } | null>(null); - const transcript = useMemo(() => { + const unread = threadRow?.unread === true; + useEffect(() => { + if (!watchedId || !unread) return; + const timer = setTimeout(() => void session.visit(watchedId).catch(() => {}), VISIT_DELAY_MS); + return () => clearTimeout(timer); + }, [session, watchedId, unread]); + + const previousTimeline = useRef<{ id: string; timeline: Timeline } | null>(null); + const timeline = useMemo(() => { if (!thread?.projection || !watchedId) return null; - const previous = previousTranscript.current?.id === watchedId ? previousTranscript.current.transcript : null; - const next = buildTranscript(thread.projection, { running, previous }); - previousTranscript.current = { id: watchedId, transcript: next }; + const previous = previousTimeline.current?.id === watchedId ? previousTimeline.current.timeline : null; + const next = buildTimeline(thread.projection, { expandAll }, previous); + previousTimeline.current = { id: watchedId, timeline: next }; return next; - }, [thread?.projection, watchedId, running]); - const pendingRequest = thread?.projection?.runtimeRequests.findLast((request) => request.status === "pending" && request.kind !== "user_input"); + }, [thread?.projection, watchedId, expandAll]); + const current = watchedId === threadId ? timeline : null; + const pendingApproval = current?.pending.approvals[0]; + const pendingInput = current?.pending.userInputs[0]; + const questionDraft = pendingInput ? (questionDrafts.get(pendingInput.requestId) ?? { index: 0, answers: {} }) : undefined; + const working = current?.isWorking ?? false; const say = (text: string, bad = false) => { setFlash({ text, bad }); - setTimeout(() => setFlash((current) => (current?.text === text ? null : current)), 4000); + setTimeout(() => setFlash((value) => (value?.text === text ? null : value)), 4000); }; - const run = (label: string, action: () => Promise) => { + const run = (label: string, action: () => Promise) => { action().then( () => say(label), (error) => say(`${label} failed: ${error instanceof Error ? error.message : String(error)}`, true), ); }; const respond = (decision: ProviderApprovalDecision) => { - if (!threadId || !pendingRequest) return say("Nothing is waiting for approval.", true); - run(decision === "decline" ? "Declined" : "Approved", () => session.respond(threadId, pendingRequest.id, decision)); + if (!threadId || !pendingApproval) return say("Nothing is waiting for approval.", true); + run(decision === "decline" ? "Declined" : "Approved", () => session.respond(threadId, pendingApproval.requestId, decision)); }; - const submit = () => { - const composer = composerRef.current; - const text = composer?.plainText.trim() ?? ""; - if (!composer || !text || !threadId) return; - composer.setText(""); - drafts.current.delete(threadId); + const clearComposer = () => { + composerRef.current?.setText(""); + if (threadId) drafts.current.delete(threadId); setComposerLines(1); - run(running ? "Queued for after the current run" : "Sent", () => session.sendMessage(threadId, text)); + setComposerEmpty(true); + }; + + /** Moves the question flow on: the next question, or the answers once all are in. */ + const advanceQuestion = (draft: QuestionDraft) => { + if (!threadId || !pendingInput) return; + const question = pendingInput.questions[draft.index]; + if (!question || resolvePendingUserInputAnswer(question, draft.answers[question.id]) === null) { + setQuestionDrafts((map) => new Map(map).set(pendingInput.requestId, draft)); + return say("Pick an option or type an answer.", true); + } + if (draft.index + 1 < pendingInput.questions.length) { + setQuestionDrafts((map) => new Map(map).set(pendingInput.requestId, { ...draft, index: draft.index + 1 })); + return; + } + const answers = buildPendingUserInputAnswers(pendingInput.questions, draft.answers); + if (!answers) return say("Some questions are unanswered.", true); + setQuestionDrafts((map) => new Map(map).set(pendingInput.requestId, draft)); + run("Answered", () => session.answer(threadId, pendingInput.requestId, answers)); + }; + + const pickOption = (optionIndex: number) => { + if (!pendingInput || !questionDraft) return; + const question = pendingInput.questions[questionDraft.index]; + const option = question?.options[optionIndex]; + if (!question || !option) return; + const draft = { ...questionDraft, answers: { ...questionDraft.answers, [question.id]: togglePendingUserInputOptionSelection(question, questionDraft.answers[question.id], option.value ?? option.label) } }; + setQuestionDrafts((map) => new Map(map).set(pendingInput.requestId, draft)); + // Single choice moves on by itself, after a beat to show the pick. + if (!question.multiSelect) setTimeout(() => advanceQuestion(draft), 200); + }; + + /** Enter in the composer; `alternate` is alt+enter, which flips steer and queue. */ + const submit = (alternate = false) => { + const text = composerRef.current?.plainText.trim() ?? ""; + if (!threadId) return; + if (pendingInput && questionDraft) { + const question = pendingInput.questions[questionDraft.index]; + if (!question) return; + const answer = text ? setPendingUserInputCustomAnswer(question, questionDraft.answers[question.id], text) : questionDraft.answers[question.id]; + clearComposer(); + return advanceQuestion({ ...questionDraft, answers: { ...questionDraft.answers, ...(answer ? { [question.id]: answer } : {}) } }); + } + if (!text) return; + clearComposer(); + if (pendingApproval) { + // As in the web composer: the message declines the request and redirects the agent. + if (pendingApproval.supportsFeedback) return run("Declined with feedback", () => session.respond(threadId, pendingApproval.requestId, "decline", text)); + return run("Declined and redirected", () => session.sendMessage(threadId, text, "steer")); + } + const dispatchMode = resolveComposerDispatchMode({ running: working, alternateModifier: alternate }); + run(dispatchMode === "queue" ? "Queued" : dispatchMode === "steer" ? "Steered" : "Sent", () => session.sendMessage(threadId, text, dispatchMode)); + }; + + const loadEarlier = () => { + if (!watchedId) return; + session.loadEarlier(watchedId).catch((error) => say(`Could not load earlier turns: ${error instanceof Error ? error.message : String(error)}`, true)); }; const quit = () => { @@ -121,11 +224,17 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI if (key.name === "pageup" || (key.ctrl && key.name === "u")) return scrollPage(-1), true; if (!attachThreadId && ((key.ctrl && key.name === "n") || (key.meta && key.name === "down"))) return move(1), true; if (!attachThreadId && ((key.ctrl && key.name === "p") || (key.meta && key.name === "up"))) return move(-1), true; + if (mode === "input" && key.meta && key.name === "return") return submit(true), true; return false; }; useKeyboard((key) => { if (globalKey(key)) return key.preventDefault(); + const digit = /^[1-9]$/.test(key.name) && !key.ctrl && !key.meta ? Number(key.name) - 1 : -1; + if (digit >= 0 && pendingInput && (mode === "nav" || (mode === "input" && composerEmpty))) { + pickOption(digit); + return key.preventDefault(); + } if (mode === "input" || mode === "filter") { if (key.name === "escape") { setMode("nav"); @@ -146,11 +255,18 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI case "g": return key.shift ? scroll?.scrollTo(scroll.scrollHeight) : scroll?.scrollTo(0); case "e": - return setExpandWork((value) => !value); + return setExpandAll((value) => !value); + case "o": + return loadEarlier(); + case "z": + return setShowFolded((value) => !value); case "y": return respond(key.shift ? "acceptForSession" : "accept"); case "n": return respond("decline"); + case "x": + if (threadId && pendingInput?.dismissible) run("Dismissed", () => session.dismissQuestion(threadId, pendingInput.requestId)); + return; case "s": if (threadId && key.shift) run("Stop requested", () => session.stopThread(threadId)); return; @@ -165,16 +281,6 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI } }); - const counts = useMemo(() => { - let needs = 0; - let active = 0; - for (const row of threadRows(shell.snapshot, { recentLimit: 0 })) { - if (row.group === "needs-you") needs++; - else if (row.group === "running") active++; - } - return { needs, active }; - }, [shell.snapshot]); - const status = shell.status.type === "error" ? `error: ${shell.status.message}` @@ -184,10 +290,28 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI ? "reconnecting…" : (shell.serverUrl ?? ""); const listWidth = attachThreadId ? 0 : Math.min(46, Math.max(28, Math.floor(width * 0.3))); - const subtitle = threadShell - ? [threadShell.modelSelection.model === "default" ? "" : threadShell.modelSelection.model, threadShell.branch, relativeTime(lastActivity(threadShell))].filter(Boolean).join(" · ") - : ""; const composerHeight = Math.min(MAX_COMPOSER_LINES, composerLines) + 2; + const placeholder = + mode !== "input" + ? "Press i to type" + : pendingApproval + ? pendingApproval.supportsFeedback + ? "Send feedback to decline this request" + : "Send a message to decline and redirect the agent" + : pendingInput + ? "Type your own answer, or leave this blank to use the selected option" + : working + ? "Steer the agent (alt+enter to queue instead)" + : "Ask anything"; + const footer = threadShell + ? [ + threadShell.modelSelection.model === "default" ? "" : threadShell.modelSelection.model, + threadShell.interactionMode === "plan" ? "Plan" : "Build", + threadShell.runtimeMode === "full-access" ? "" : (RUNTIME_MODE_LABELS[threadShell.runtimeMode] ?? threadShell.runtimeMode), + ] + .filter(Boolean) + .join(" · ") + : ""; return ( @@ -195,23 +319,24 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI tui3 - {` ${status}`} - - {counts.needs > 0 ? {`● ${counts.needs} need you `} : null} - {`◐ ${counts.active} running`} + {` ${status}`} - {attachThreadId ? null : } + {attachThreadId ? null : ( + + )} {threadId ? ( ) : ( @@ -219,6 +344,7 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI {shell.snapshot ? "No thread selected." : "Waiting for threads…"} )} + {mode !== "filter" && pendingInput && questionDraft ? : null} {mode === "filter" ? ( setFilter(value)} onSubmit={() => setMode("nav")} /> @@ -240,39 +366,51 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI ref={composerRef} focused={mode === "input"} initialValue={drafts.current.get(threadId) ?? ""} - placeholder={mode === "input" ? (running ? "Message (queued until the current run finishes)" : "Message") : "Press i to type"} + placeholder={placeholder} placeholderColor={colors.faint} textColor={colors.text} keyBindings={[...COMPOSER_KEYS]} - onSubmit={submit} + onSubmit={() => submit()} onContentChange={() => { const text = composerRef.current?.plainText ?? ""; if (text) drafts.current.set(threadId, text); else drafts.current.delete(threadId); setComposerLines(Math.max(1, text.split("\n").length)); + setComposerEmpty(text.trim() === ""); }} /> ) : null} + {mode !== "filter" && threadId ? ( + + {footer} + + ) : null} - {flash ? {flash.text} : {hints(mode, Boolean(pendingRequest), Boolean(attachThreadId))}} + {flash ? ( + {flash.text} + ) : ( + {hints(mode, { approval: Boolean(pendingApproval), question: Boolean(pendingInput), working, attached: Boolean(attachThreadId) })} + )} ); } -function hints(mode: Mode, pending: boolean, attached: boolean): string { +function hints(mode: Mode, state: { readonly approval: boolean; readonly question: boolean; readonly working: boolean; readonly attached: boolean }): string { if (mode === "filter") return "enter done · esc close"; if (mode === "input") { - const parts = ["enter send", "shift+enter newline", "esc navigate"]; - if (!attached) parts.push("ctrl+n/p switch thread"); - if (pending) parts.unshift("approval waiting: esc, then y/n"); + const parts = [state.working ? "enter steer · alt+enter queue" : "enter send", "shift+enter newline", "esc navigate"]; + if (state.question) parts.unshift("1-9 pick"); + if (state.approval) parts.unshift("approval waiting: esc, then y/n"); + if (!state.attached) parts.push("ctrl+n/p thread"); return parts.join(" · "); } - const parts = attached ? ["j/k scroll"] : ["j/k threads", "/ filter"]; - parts.push("i type", "e expand work", "pgup/pgdn scroll", "S stop", "q quit"); - if (pending) parts.unshift("y accept · Y session · n decline"); + const parts = state.attached ? ["j/k scroll"] : ["j/k threads", "/ filter", "z settled"]; + parts.push("i type", "e expand", "o earlier", "S stop", "q quit"); + if (state.question) parts.unshift("1-9 pick · x dismiss"); + if (state.approval) parts.unshift("y approve · Y always · n decline"); return parts.join(" · "); } diff --git a/src/ui/QuestionPanel.tsx b/src/ui/QuestionPanel.tsx new file mode 100644 index 0000000..860bf85 --- /dev/null +++ b/src/ui/QuestionPanel.tsx @@ -0,0 +1,42 @@ +import type { ThreadPendingUserInput } from "@t3tools/client-runtime/state/thread-requests"; +import { isPendingUserInputOptionSelected, type PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input"; + +import { colors } from "./theme.ts"; + +/** + * The web composer's pending-input panel: header with progress, the question, + * and its options with digit shortcuts. The composer below takes a typed answer. + */ +export function QuestionPanel(props: { + readonly request: ThreadPendingUserInput; + readonly index: number; + readonly draft: PendingUserInputDraftAnswer | undefined; +}) { + const { request, index, draft } = props; + const question = request.questions[index]; + if (!question) return null; + const total = request.questions.length; + return ( + + + + {question.header} + + + {total > 1 ? `${index + 1}/${total}` : ""} + + {question.question} + {question.options.slice(0, 9).map((option, optionIndex) => { + const selected = isPendingUserInputOptionSelected(question, draft, option.value ?? option.label); + const mark = question.multiSelect ? (selected ? "☑" : "☐") : selected ? "●" : "○"; + return ( + + {`${optionIndex + 1} ${mark} `} + {option.label} + {option.description ? ` ${option.description}` : ""} + + ); + })} + + ); +} diff --git a/src/ui/ThreadList.tsx b/src/ui/ThreadList.tsx index a846f13..4db0676 100644 --- a/src/ui/ThreadList.tsx +++ b/src/ui/ThreadList.tsx @@ -1,69 +1,78 @@ -import { GROUP_LABELS, lastActivity, relativeTime, type ThreadRow } from "../model/threads.ts"; -import { colors } from "./theme.ts"; +import { needsAttention, relativeTime, rowTime, SECTION_LABELS, statusLabel, type Section, type ThreadRow } from "../model/threads.ts"; +import { colors, statusColor } from "./theme.ts"; -const STATUS_GLYPH: Record = { - "needs-you": { glyph: "●", color: colors.warn }, - running: { glyph: "◐", color: colors.accent }, - failed: { glyph: "✕", color: colors.bad }, - interrupted: { glyph: "◌", color: colors.muted }, - completed: { glyph: "✓", color: colors.faint }, - idle: { glyph: "·", color: colors.faint }, -}; - -function glyphFor(row: ThreadRow) { - if (row.group !== "recent") return STATUS_GLYPH[row.group]!; - return STATUS_GLYPH[row.thread.status] ?? STATUS_GLYPH.idle!; -} - -export function ThreadList(props: { readonly rows: readonly ThreadRow[]; readonly selected: number; readonly focused: boolean; readonly width: number; readonly height: number; readonly filter: string }) { - const { rows, selected, focused, width, height } = props; - // Rows take two lines and up to three group headers take one each; keep the selection in view. - const visibleCount = Math.max(1, Math.floor((height - 3) / 2)); +/** + * The web sidebar as a list: section headers, then two-line rows of + * project + status (or time), and the title, bold when it needs you and + * dimmed while it works or once read. + */ +export function ThreadList(props: { + readonly rows: readonly ThreadRow[]; + /** Sections folded to a header with a count, like the web's Snoozed and Settled. */ + readonly collapsed: ReadonlyMap; + readonly selected: number; + readonly focused: boolean; + readonly width: number; + readonly height: number; + readonly filter: string; + readonly now: number; +}) { + const { rows, selected, focused, width, height, now } = props; + // Rows take two lines plus a header per section; keep the selection in view. + const visibleCount = Math.max(1, Math.floor((height - 6) / 2)); const start = Math.max(0, Math.min(selected - Math.floor(visibleCount / 2), rows.length - visibleCount)); const windowRows = rows.slice(start, start + visibleCount); - const titleWidth = Math.max(8, width - 12); - const now = Date.now(); + const inner = Math.max(8, width - 3); + // Active goes unlabelled when it leads the list, as in the web sidebar. + const labelActive = rows.some((row) => row.section === "pinned"); const lines: React.ReactNode[] = []; - let previousGroup = start > 0 ? rows[start - 1]?.group : undefined; + let previousSection = start > 0 ? rows[start - 1]?.section : undefined; windowRows.forEach((row, offset) => { const index = start + offset; - if (row.group !== previousGroup) { - lines.push( - - {GROUP_LABELS[row.group]} - , - ); - previousGroup = row.group; + if (row.section !== previousSection) { + if (row.section !== "active" || labelActive) lines.push(); + else if (previousSection !== undefined) lines.push( ); + previousSection = row.section; } - const { glyph, color } = glyphFor(row); const isSelected = index === selected; - const title = truncate(row.thread.title || "(untitled)", titleWidth); + const status = statusLabel(row, now); + const right = status?.text ?? relativeTime(rowTime(row.thread), now); + const left = truncate(row.projectName || "No project", Math.max(4, inner - right.length - 1)); + const attention = needsAttention(row); + const recede = !isSelected && (row.status === "working" || row.status === "waiting" || (row.status === "ready" && !row.unread)); + const title = truncate(row.thread.title || "New thread", inner); lines.push( - - {` ${glyph} `} - - {title} - {truncate(`${row.projectName} · ${relativeTime(lastActivity(row.thread), now)}`, titleWidth)} + + + {left} + + {right} + {attention ? {title} : title} , ); }); + const collapsed = [...props.collapsed].filter(([, count]) => count > 0); return ( - + {props.filter ? {` /${props.filter}`} : null} - {rows.length === 0 ? no threads : lines} + {rows.length === 0 ? {props.filter ? " no matches" : " no threads"} : lines} + + {collapsed.map(([section, count]) => ( + {` › ${SECTION_LABELS[section]} ${count}`} + ))} ); } +function SectionHeader({ label }: { readonly label: string }) { + return ( + + {label} + + ); +} + function truncate(text: string, width: number): string { const single = text.replace(/\s+/g, " "); return single.length > width ? `${single.slice(0, Math.max(0, width - 1))}…` : single; diff --git a/src/ui/ThreadView.tsx b/src/ui/ThreadView.tsx index 119e26b..dc35625 100644 --- a/src/ui/ThreadView.tsx +++ b/src/ui/ThreadView.tsx @@ -1,145 +1,248 @@ import type { ScrollBoxRenderable } from "@opentui/core"; +import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models"; +import { liveThoughtLine, workEntryDisplayIndicatesToolFailure, type ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation"; import { memo, type RefObject } from "react"; -import { summarizeWork, type Segment, type Step, type Transcript } from "../model/transcript.ts"; +import type { ThreadHistory } from "../client/session.ts"; +import { liveWorkEntryLabel, workEntryDisplayLabel, type MessagesTimelineRow, type Timeline, type WorkLogEntry } from "../model/timeline.ts"; +import { blockFor } from "../model/transcript.ts"; import { colors, getMarkdownStyle, toneColor } from "./theme.ts"; +/** The conversation, row for row as the web app derives it (MessagesTimeline.logic). */ export function ThreadView(props: { + readonly project: string; readonly title: string; - readonly subtitle: string; - readonly transcript: Transcript | null; + readonly detail: string; + readonly timeline: Timeline | null; + readonly history: ThreadHistory | null; readonly loading: boolean; readonly error?: string | undefined; - readonly working: boolean; - readonly expandWork: boolean; + readonly workspaceRoot: string | undefined; + readonly now: number; readonly scrollRef: RefObject; }) { - const { transcript } = props; - const last = transcript?.segments.at(-1); - // The folded work line already says it's working; otherwise show it at the bottom. - const showWorking = props.working && !(last?.kind === "work" && last.active) && !(last?.kind === "assistant" && last.streaming); + const { timeline, history } = props; + const pendingIds = new Set(timeline?.pending.approvals.map((approval) => approval.requestId) ?? []); return ( + {props.project ? `${props.project} / ` : ""} {props.title} - {props.subtitle ? ` ${props.subtitle}` : ""} + + {props.detail} {props.error ? {props.error} : null} - {props.loading && !transcript ? loading… : null} - {transcript && transcript.hiddenCount > 0 ? {`… ${transcript.hiddenCount} earlier items`} : null} - {transcript?.segments.map((segment) => )} - {showWorking ? ◐ working… : null} + {props.loading && !timeline ? Loading… : null} + {history?.hasMore || history?.error ? : null} + {timeline?.rows.map((row) => ( + + ))} ); } -/** Memoized: unchanged segments keep their object identity across updates, so only what changed re-renders. */ -const SegmentView = memo(function SegmentView({ segment, expandWork }: { readonly segment: Segment; readonly expandWork: boolean }) { - switch (segment.kind) { - case "user": { - const { text, hidden } = expandWork ? { text: segment.text.trim(), hidden: 0 } : clip(segment.text.trim()); +function LoadEarlier({ history }: { readonly history: ThreadHistory }) { + const label = history.loading ? "Loading earlier turns…" : history.error ? `Could not load earlier turns: ${history.error} (o to retry)` : "Load earlier turns (o)"; + return ; +} + +function Divider({ label, color }: { readonly label: string; readonly color: string }) { + return ( + + + {` ${label} `} + + + ); +} + +/** + * Memoized: computeStableMessagesTimelineRows keeps unchanged rows identical, + * so a streamed update re-renders only its own rows. `now` is nonzero only for + * the working row, which ticks. + */ +const Row = memo(function Row(props: { + readonly row: MessagesTimelineRow; + readonly pending: boolean; + readonly workspaceRoot: string | undefined; + readonly now: number; + readonly workStartedAt: string | null; +}) { + const { row, workspaceRoot } = props; + switch (row.kind) { + case "message": { + const { message } = row; + if (message.role === "user") return ; + if (message.role === "system") return {message.text}; return ( - - {text} - {hidden > 0 ? {`… ${hidden} more lines (e to expand)`} : null} + + ); } - case "assistant": + case "turn-fold": + case "attempt-fold": + // The finished turn's work, folded: the web's turn separator. return ( - - + + {`${row.label} ${row.expanded ? "⌄" : "›"}`} + + ); + case "work-toggle": + return ( + + {`${SUMMARY_GLYPH[row.summaryKind] ?? "•"} ${row.summary} ${row.expanded ? "⌄" : "›"}`} ); case "work": - return expandWork ? : ; - case "approval": return ( - - - {segment.pending ? "Needs approval" : "Approval"} - - {segment.title} - {segment.detail ? {segment.detail} : null} - {segment.pending ? esc, then y accept · Y accept for session · n decline : null} - - ); - case "question": - return ( - - - {segment.pending ? "Question for you" : "Question"} - - {segment.questions.map((question, index) => ( - {question} + + {row.groupedEntries.map((entry) => ( + ))} - {segment.pending ? Answer this in the T3 Code app for now. : null} ); - case "alert": - return {segment.text}; + case "work-live": + return ( + + {row.thought?.detail ? {`∴ ${liveThoughtLine(row.thought.detail)}`} : null} + {`${row.active ? "◐" : glyphFor(row.entry)} ${liveWorkEntryLabel(row.entry, workspaceRoot, row.active)}`} + + ); + case "working": { + const since = props.workStartedAt ? Date.parse(props.workStartedAt) : NaN; + const verb = row.compacting ? "Compacting" : "Working"; + return {Number.isFinite(since) ? `◐ ${verb} for ${formatWorkingDurationLabel(props.now - since)}` : `◐ ${verb}…`}; + } + case "thinking": + return ∴ Thinking…; + case "context-compaction": + return ; + case "proposed-plan": + return ( + + + Plan + + + + ); + case "event": + return ; + case "worktree-setup": + return ◐ Setting up worktree…; + default: + // assistant-meta, html-render, mcp-app: nothing a terminal can show. + return null; } }); -function FoldedWork({ steps, active }: { readonly steps: readonly Step[]; readonly active: boolean }) { - const latest = active ? steps.at(-1) : undefined; +const USER_FOLD_LINES = 8; +const USER_FOLD_CHARS = 600; + +/** The web's user bubble: right-aligned, at most 80% wide, folded past 8 lines or 600 characters. */ +function UserMessage({ text }: { readonly text: string }) { + const trimmed = text.trim(); + const lines = trimmed.split("\n"); + let shown = lines.slice(0, USER_FOLD_LINES).join("\n"); + if (shown.length > USER_FOLD_CHARS) shown = `${shown.slice(0, USER_FOLD_CHARS).trimEnd()}…`; + const folded = shown.length < trimmed.length; return ( - - {`${active ? "◐" : "▸"} ${summarizeWork(steps)}`} - {latest ? {` ${stepLine(latest)}`} : null} + + {shown} + {folded ? {`… ${Math.max(1, lines.length - shown.split("\n").length)} more lines`} : null} ); } -function ExpandedWork({ steps }: { readonly steps: readonly Step[] }) { - return ( - - {steps.map((step) => ( - - {stepLine(step)} - {step.kind === "tool" && step.detail ? {indent(step.detail, " ")} : null} - - ))} - - ); +function WorkEntry({ entry, label }: { readonly entry: WorkLogEntry; readonly label: string }) { + const failed = workEntryDisplayIndicatesToolFailure(entry); + const tone = failed || entry.tone === "error" ? colors.bad : entry.tone === "thinking" ? colors.faint : colors.muted; + return {`${failed ? "✕" : glyphFor(entry)} ${firstLine(label)}`}; } -function stepLine(step: Step): string { - switch (step.kind) { - case "tool": - return `${step.icon} ${step.label}`; - case "reasoning": - return `∴ ${firstLine(step.text)}`; +function EventRow({ item, pending }: { readonly item: MessagesTimelineRow extends infer R ? (R extends { kind: "event"; projectedItem: { item: infer I } } ? I : never) : never; readonly pending: boolean }) { + if (item.type === "approval_request" && pending) { + return ( + + + {approvalTitle(item.requestKind)} + + {item.prompt ? {item.prompt} : null} + {item.reason ? {item.reason} : null} + Waiting for approval · y Approve · Y Always allow this session · n Decline + + ); + } + const block = blockFor(item, new Set()); + if (!block) return null; + switch (block.kind) { case "notice": - return `· ${step.text}`; + return {block.text}; + case "tool": + return {`${block.icon} ${block.label}`}; + case "approval": + return {`Approval requested: ${block.title}`}; + case "question": + return {block.pending ? "Input requested" : "Answered questions"}; + default: + return null; } } -const CLIP_LINES = 6; -const CLIP_CHARS = 480; +function approvalTitle(kind: string): string { + if (kind.includes("command")) return "Command approval"; + if (kind.includes("read")) return "File read approval"; + if (kind.includes("file")) return "File change approval"; + if (kind.includes("access")) return "App access approval"; + if (kind.includes("permission")) return "App permission approval"; + return "Approval"; +} -/** Long prompts (delegation briefs, pasted logs) shrink to their opening lines. */ -function clip(text: string): { readonly text: string; readonly hidden: number } { - const lines = text.split("\n"); - let kept = lines.slice(0, CLIP_LINES).join("\n"); - if (kept.length > CLIP_CHARS) kept = `${kept.slice(0, CLIP_CHARS).trimEnd()}…`; - const keptLines = kept.split("\n").length; - const hidden = lines.length - keptLines; - return kept.length < text.length ? { text: kept, hidden: Math.max(hidden, 1) } : { text, hidden: 0 }; +function eventRequestId(row: Extract): string | undefined { + const item = row.projectedItem.item; + return item.type === "approval_request" ? item.requestId : undefined; +} + +/** Terminal stand-ins for the web's lucide icons. */ +const SUMMARY_GLYPH: Partial> = { + read: "◉", + edit: "✎", + command: "$", + "code-search": "⌕", + search: "⌕", + browser: "◍", + reasoning: "∴", + "thread-create": "↳", + "agent-tool": "↳", + "pull-request": "⇅", + "dynamic-tool": "⚙", + other: "⚙", + mixed: "•", +}; + +function glyphFor(entry: WorkLogEntry): string { + if (entry.tone === "thinking" || entry.itemType === "reasoning") return "∴"; + if (entry.command) return "$"; + if (entry.changedFiles?.length) return "✎"; + if (entry.itemType === "subagent") return "↳"; + if (entry.itemType === "file_search" || entry.itemType === "web_search") return "⌕"; + if (entry.itemType === "todo_list") return "☐"; + return "·"; } function firstLine(text: string): string { - const line = (text.trim().split("\n")[0] ?? "").replace(/\*\*(.+?)\*\*/g, "$1"); - return line.length > 120 ? `${line.slice(0, 117)}…` : line; -} - -function indent(text: string, prefix: string): string { - return text - .split("\n") - .map((line) => prefix + line) - .join("\n"); + const line = (text.trim().split("\n")[0] ?? "").replace(/\s+/g, " "); + return line.length > 200 ? `${line.slice(0, 197)}…` : line; } diff --git a/src/ui/theme.ts b/src/ui/theme.ts index c524bd6..5d097f0 100644 --- a/src/ui/theme.ts +++ b/src/ui/theme.ts @@ -1,5 +1,6 @@ import { SyntaxStyle } from "@opentui/core"; +import type { StatusTone } from "../model/threads.ts"; import type { Tone } from "../model/transcript.ts"; export const colors = { @@ -17,8 +18,21 @@ export const colors = { bad: "#f7768e", warn: "#e0af68", selectedBg: "#283457", + /** The web app's sky / indigo / violet status hues. */ + info: "#7dcfff", + input: "#bb9af7", + plan: "#c099ff", } as const; +export const statusColor: Record = { + info: colors.info, + muted: colors.muted, + warn: colors.warn, + input: colors.input, + bad: colors.bad, + good: colors.good, +}; + export const toneColor: Record = { normal: colors.text, muted: colors.muted, diff --git a/test/commands.test.ts b/test/commands.test.ts index 41fd931..b9fec20 100644 --- a/test/commands.test.ts +++ b/test/commands.test.ts @@ -19,12 +19,35 @@ const isCommand = Schema.is(OrchestrationV2Command); const threadId = ThreadId.make("thread-1"); describe("commands tui3 dispatches", () => { - test("a queued message is a valid message.dispatch", async () => { + test("messages dispatch like the web composer: auto, steer or queue", async () => { const { session, sent } = capturingSession(); await session.sendMessage(threadId, "hello"); - expect(sent).toHaveLength(1); + await session.sendMessage(threadId, "change course", "steer"); + await session.sendMessage(threadId, "after that", "queue"); + expect(sent.every(isCommand)).toBe(true); + expect(sent[0]).toMatchObject({ type: "message.dispatch", threadId, text: "hello", dispatchMode: { type: "start_immediately" }, deliveryIntent: "auto" }); + expect(sent[1]).toMatchObject({ dispatchMode: { type: "start_immediately" }, deliveryIntent: "steer" }); + expect(sent[2]).toMatchObject({ dispatchMode: { type: "queue_after_active" } }); + expect(sent[2]).not.toHaveProperty("deliveryIntent"); + }); + + test("declining with feedback, answering and dismissing questions are valid", async () => { + const { session, sent } = capturingSession(); + const requestId = RuntimeRequestId.make("req-1"); + await session.respond(threadId, requestId, "decline", "use the staging bucket"); + await session.answer(threadId, requestId, { q1: "yes", q2: ["a", "b"] }); + await session.dismissQuestion(threadId, requestId); + expect(sent.every(isCommand)).toBe(true); + expect(sent[0]).toMatchObject({ decision: "decline", feedback: "use the staging bucket" }); + expect(sent[1]).toMatchObject({ type: "runtime-request.respond", answers: { q1: "yes", q2: ["a", "b"] } }); + expect(sent[2]).toMatchObject({ type: "thread.user-input.dismiss" }); + }); + + test("a visit is a valid thread.visit", async () => { + const { session, sent } = capturingSession(); + await session.visit(threadId); expect(isCommand(sent[0])).toBe(true); - expect(sent[0]).toMatchObject({ type: "message.dispatch", threadId, text: "hello", dispatchMode: { type: "queue_after_active" } }); + expect(sent[0]).toMatchObject({ type: "thread.visit", threadId, opened: true }); }); test("an approval is a valid runtime-request.respond", async () => { diff --git a/test/threads.test.ts b/test/threads.test.ts index 6819c6c..5228428 100644 --- a/test/threads.test.ts +++ b/test/threads.test.ts @@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test"; import type { OrchestrationV2ShellSnapshot } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; -import { findThread, relativeTime, threadRows } from "../src/model/threads.ts"; +import { findThread, relativeTime, statusLabel, threadRows } from "../src/model/threads.ts"; const at = (ms: number) => DateTime.makeUnsafe(ms); const thread = (id: string, title: string, updated: number, extra: Record = {}) => ({ @@ -11,7 +11,23 @@ const thread = (id: string, title: string, updated: number, extra: Record { - test("orders needs-you, then running, then recent by activity", () => { - expect(threadRows(snapshot).map((row) => row.thread.id as string)).toEqual(["t-waiting", "t-running", "t-new", "mcp:launch:aaaa1111"]); + test("uses the web sidebar's sections and leaves subagents under their parent", () => { + expect(threadRows(snapshot).map((row) => [row.thread.id as string, row.section])).toEqual([ + ["t-new", "active"], + ["mcp:launch:aaaa1111", "active"], + ["t-waiting", "active"], + ["t-running", "working"], + ["t-settled", "settled"], + ]); }); - test("filters by title or project and caps recent rows", () => { + test("shows the sidebar's status words", () => { + const byId = new Map(threadRows(snapshot).map((row) => [row.thread.id as string, row])); + expect(statusLabel(byId.get("t-waiting")!)?.text).toBe("Approval"); + expect(statusLabel(byId.get("t-new")!)?.text).toBe("Done"); + expect(statusLabel(byId.get("mcp:launch:aaaa1111")!)).toBeNull(); + expect(statusLabel(byId.get("t-running")!, 2_000 + 75_000)?.text).toBe("Working 1m"); + }); + + test("filters by title or project", () => { expect(threadRows(snapshot, { query: "BUSY" }).map((row) => row.thread.id as string)).toEqual(["t-running"]); - expect(threadRows(snapshot, { query: "tasknotes" })).toHaveLength(4); - expect(threadRows(snapshot, { recentLimit: 1 }).map((row) => row.group)).toEqual(["needs-you", "running", "recent"]); + expect(threadRows(snapshot, { query: "tasknotes" })).toHaveLength(5); }); }); @@ -46,6 +77,7 @@ describe("findThread", () => { }); test("relativeTime", () => { + expect(relativeTime(0, 2_000)).toBe("now"); expect(relativeTime(0, 45_000)).toBe("45s"); expect(relativeTime(0, 3 * 3600_000)).toBe("3h"); }); diff --git a/test/transcript.test.ts b/test/transcript.test.ts index f5ab93f..ab33c87 100644 --- a/test/transcript.test.ts +++ b/test/transcript.test.ts @@ -27,52 +27,3 @@ describe("blockFor", () => { expect(blockFor(item({ type: "checkpoint" }), new Set())).toBeNull(); }); }); - -import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; -import { buildTranscript, summarizeWork } from "../src/model/transcript.ts"; - -const projectionOf = (items: OrchestrationV2TurnItem[], pendingIds: string[] = []) => - ({ - runtimeRequests: pendingIds.map((id) => ({ id, status: "pending" })), - visibleTurnItems: items.map((entry, position) => ({ position, item: entry })), - }) as unknown as OrchestrationV2ThreadProjection; - -let counter = 0; -const turn = (fields: Record) => item({ id: `i${counter++}`, ...fields }); - -describe("buildTranscript", () => { - test("folds runs of work between messages into one segment", () => { - const transcript = buildTranscript( - projectionOf([ - turn({ type: "user_message", text: "fix it" }), - turn({ type: "command_execution", input: "ls" }), - turn({ type: "reasoning", text: "thinking", streaming: false }), - turn({ type: "file_change", fileName: "a.ts" }), - turn({ type: "assistant_message", text: "done", streaming: false }), - ]), - ); - expect(transcript.segments.map((segment) => segment.kind)).toEqual(["user", "work", "assistant"]); - const work = transcript.segments[1]; - expect(work?.kind === "work" && summarizeWork(work.steps)).toBe("1 command · 1 edit"); - }); - - test("marks trailing work active while the thread runs", () => { - const transcript = buildTranscript(projectionOf([turn({ type: "command_execution", input: "make" })]), { running: true }); - expect(transcript.segments[0]).toMatchObject({ kind: "work", active: true }); - }); - - test("errors break out of folded work", () => { - const transcript = buildTranscript(projectionOf([turn({ type: "command_execution", input: "a" }), turn({ type: "error", failure: { message: "boom" } }), turn({ type: "command_execution", input: "b" })])); - expect(transcript.segments.map((segment) => segment.kind)).toEqual(["work", "alert", "work"]); - }); - - test("reuses unchanged segments so the view can skip them", () => { - const user = turn({ type: "user_message", text: "hi" }); - const command = turn({ type: "command_execution", input: "ls" }); - const first = buildTranscript(projectionOf([user, command, turn({ type: "assistant_message", text: "He", streaming: true })])); - const second = buildTranscript(projectionOf([user, command, turn({ type: "assistant_message", text: "Hello", streaming: true })]), { previous: first }); - expect(second.segments[0]).toBe(first.segments[0]!); - expect(second.segments[1]).toBe(first.segments[1]!); - expect(second.segments[2]).not.toBe(first.segments[2]!); - }); -});