Merge branch 'worktree-agent-a2220433c67c864f1'
This commit is contained in:
@@ -27,6 +27,7 @@ class ChatShellRun {
|
||||
this.outputEnd = 0,
|
||||
this.outputBytes = 0,
|
||||
this.gap = false,
|
||||
this.snapshot = false,
|
||||
this.terminal = false,
|
||||
this.cols = 0,
|
||||
this.rows = 0,
|
||||
@@ -59,6 +60,11 @@ class ChatShellRun {
|
||||
/// stretch of what the command wrote.
|
||||
final bool gap;
|
||||
|
||||
/// True when [output] starts with the server's redraw of the terminal's
|
||||
/// state at [outputStart] (screens, scrollback, cursor and modes) instead
|
||||
/// of raw output: nothing earlier is missing from what it shows.
|
||||
final bool snapshot;
|
||||
|
||||
/// True when the command runs in a pseudo-terminal of [cols] x [rows]:
|
||||
/// [output] is then the raw terminal stream and it accepts typed input
|
||||
/// while it runs. Older runs (and servers without terminals) are plain.
|
||||
@@ -78,7 +84,7 @@ class ChatShellRun {
|
||||
final bool purged;
|
||||
|
||||
/// Whether earlier output is not shown here.
|
||||
bool get truncated => outputStart > 0 || gap;
|
||||
bool get truncated => !snapshot && (outputStart > 0 || gap);
|
||||
|
||||
ChatShellRunState get state => switch (status) {
|
||||
'running' => ChatShellRunState.running,
|
||||
@@ -144,6 +150,7 @@ class ChatShellRun {
|
||||
? next.outputBytes
|
||||
: outputBytes,
|
||||
gap: gap,
|
||||
snapshot: snapshot,
|
||||
terminal: next.terminal || terminal,
|
||||
cols: next.cols == 0 ? cols : next.cols,
|
||||
rows: next.rows == 0 ? rows : next.rows,
|
||||
@@ -180,6 +187,7 @@ class ChatShellRun {
|
||||
outputEnd: end,
|
||||
outputBytes: end > outputBytes ? end : outputBytes,
|
||||
gap: gap || dropped || (!contiguous && offset > 0),
|
||||
snapshot: snapshot && contiguous && !dropped,
|
||||
terminal: terminal,
|
||||
cols: cols,
|
||||
rows: rows,
|
||||
|
||||
@@ -113,8 +113,12 @@ class ChatShellTerminalSession {
|
||||
}
|
||||
|
||||
/// Draws [run]'s held output from scratch: on open, after a gap and after
|
||||
/// a readback replaced the card's copy. Answers the emulator gives to old
|
||||
/// queries in that output are not sent: the process asked them long ago.
|
||||
/// a readback replaced the card's copy. A machine terminal's read from
|
||||
/// before the server's tail is the server's snapshot
|
||||
/// ([ChatShellRun.snapshot]), which resets the emulator and restores the
|
||||
/// screens, scrollback, cursor and modes; it is drawn the same way.
|
||||
/// Answers the emulator gives to old queries in that output are not sent:
|
||||
/// the process asked them long ago.
|
||||
/// A large output is drawn in slices across turns of the event loop
|
||||
/// (ChatShellTerminalFeed), so it never stalls the UI.
|
||||
void replay(ChatShellRun run) {
|
||||
@@ -126,6 +130,9 @@ class ChatShellTerminalSession {
|
||||
terminal.useMainBuffer();
|
||||
terminal.buffer.clear();
|
||||
terminal.buffer.setCursor(0, 0);
|
||||
// A full reset (RIS): modes a program set in the output drawn before
|
||||
// (mouse reporting, bracketed paste, the alternate screen) end too.
|
||||
terminal.write('\x1bc');
|
||||
terminal.setCursorVisibleMode(true);
|
||||
terminal.write('\x1b[0m');
|
||||
if (run.truncated) {
|
||||
|
||||
@@ -25,17 +25,29 @@ class TerminalStream {
|
||||
int end = 0;
|
||||
String stream = '';
|
||||
|
||||
/// Whether [text] starts with the server's snapshot of the terminal's
|
||||
/// state at [start] rather than raw output (until its start is dropped).
|
||||
bool snapshot = false;
|
||||
|
||||
/// Whether nothing was received yet.
|
||||
bool get empty => stream.isEmpty && end == 0;
|
||||
|
||||
/// Replaces the held copy with a read of the server's retained tail,
|
||||
/// covering bytes [outputStart, outputEnd) (the server's offsets: the
|
||||
/// text's own UTF-8 length differs where invalid bytes were replaced).
|
||||
void reset(String output, int outputStart, int outputEnd, String name) {
|
||||
/// text's own UTF-8 length differs where invalid bytes were replaced), or
|
||||
/// with its [snapshot] of the terminal at [outputStart].
|
||||
void reset(
|
||||
String output,
|
||||
int outputStart,
|
||||
int outputEnd,
|
||||
String name, {
|
||||
bool snapshot = false,
|
||||
}) {
|
||||
text = output;
|
||||
start = outputStart;
|
||||
end = outputEnd;
|
||||
stream = name;
|
||||
this.snapshot = snapshot;
|
||||
_bound();
|
||||
}
|
||||
|
||||
@@ -59,6 +71,7 @@ class TerminalStream {
|
||||
if (unit >= 0xDC00 && unit <= 0xDFFF) cut++;
|
||||
final dropped = text.substring(0, cut);
|
||||
text = text.substring(cut);
|
||||
snapshot = false;
|
||||
// The server's offsets are not re-derived from the text: only the
|
||||
// dropped part is measured (approximately, for replaced bytes).
|
||||
start += utf8.encode(dropped).length;
|
||||
|
||||
@@ -95,6 +95,7 @@ class TerminalTab extends ChangeNotifier with TerminalTabEvents {
|
||||
output: _stream.text,
|
||||
outputStart: _stream.start,
|
||||
outputEnd: _stream.end,
|
||||
snapshot: _stream.snapshot,
|
||||
terminal: true,
|
||||
cols: _info.cols,
|
||||
rows: _info.rows,
|
||||
@@ -170,8 +171,12 @@ class TerminalTab extends ChangeNotifier with TerminalTabEvents {
|
||||
// The server counts this connection's window from the reply's end.
|
||||
_window = (record['window'] as num?)?.toInt() ?? 0;
|
||||
_acked = end;
|
||||
if (after == null || start > _stream.end) {
|
||||
_stream.reset(output, start, end, info.stream);
|
||||
// A read from before the server's retained tail (a new page, a reload,
|
||||
// a gap) is its snapshot of the terminal: the screens, scrollback,
|
||||
// cursor and modes as of the reply's end.
|
||||
final snapshot = record['output_snapshot'] == true;
|
||||
if (after == null || start > _stream.end || snapshot) {
|
||||
_stream.reset(output, start, end, info.stream, snapshot: snapshot);
|
||||
session.replay(_run());
|
||||
} else {
|
||||
_append(output, start, end);
|
||||
|
||||
@@ -261,6 +261,73 @@ Emulator (`chat_shell_terminal_feed_test.dart`, 896 KiB replay): one
|
||||
synchronous write 160 ms; sliced, the same 161 ms over 20 turns, the
|
||||
longest turn 12.5 ms.
|
||||
|
||||
## Screen state across reloads (2026-11-26)
|
||||
|
||||
The server keeps each machine terminal's *state*, not only its bytes, so
|
||||
a client that attaches late is brought to the exact current screen.
|
||||
|
||||
- `internal/termstate` is a headless xterm-compatible emulator (own code;
|
||||
see "Why not a library" below). `terminal_process.go` feeds it every PTY
|
||||
read under `p.mu`, the same lock as the 1 MiB tail, so its state always
|
||||
belongs to the tail's end; `applySize` resizes it with the PTY.
|
||||
- `terminal_output` whose `after` is before the retained tail (the newest
|
||||
1 MiB; a missing `after` counts as 0) gets `output_snapshot: true`:
|
||||
`output` is the emulator's snapshot and `output_start == output_end`
|
||||
is the offset it describes; the frames that follow start there, and the
|
||||
flow window counts from it as from any reply (`terminal_screen.go`). A
|
||||
read inside the tail (an ordinary resume, or a stream not longer than
|
||||
1 MiB) is raw bytes as before.
|
||||
- The snapshot (`termstate.Snapshot`) is an escape stream for a reset
|
||||
terminal: `RIS` + `ED 3`, the title (OSC 2), the inactive alternate
|
||||
screen if it holds anything (`?47h` … `?47l`), the last 1000 scrollback
|
||||
lines and the main screen row by row (soft wraps wrap again), then, if
|
||||
the alternate screen is in use, the main screen's saved cursor and
|
||||
`?1049h` (so the program's exit restores it) and the alternate screen
|
||||
drawn row by row; then the saved cursor(s), tab stops, scroll region,
|
||||
origin mode, the cursor (a pending wrap is recreated by rewriting the
|
||||
last cell; the cell before the cursor is rewritten when it holds the last
|
||||
character, for REP), modes (DECCKM, DECKPAM, autowrap, IRM, LNM, reverse
|
||||
video, cursor blink/visibility/shape, mouse tracking 9/1000-1003 and
|
||||
encoding 1005/1006/1015, focus 1004, bracketed paste 2004, 1007), G0/G1
|
||||
character sets and SO, the pen (SGR incl. 256/RGB colours and underline
|
||||
styles) and the start of an unfinished escape sequence or OSC string. An
|
||||
unfinished UTF-8 character is left out (`output_end` is before it; the
|
||||
next frame carries it whole).
|
||||
- Client: `TerminalTab._read` resets its held copy and replays when the
|
||||
reply is a snapshot (`TerminalStream.snapshot`, `ChatShellRun.snapshot`:
|
||||
no "earlier output was dropped" line). `ChatShellTerminalSession.replay`
|
||||
now writes RIS before any replay, so a raw replay no longer inherits
|
||||
stale mouse/paste/alt-screen modes either.
|
||||
- Chat shell interactive commands are not covered: their readbacks come
|
||||
from the run record (DB snapshot every 2 s of the raw tail) on a
|
||||
separate path; they get only the RIS-on-replay change.
|
||||
|
||||
Why not a library: `github.com/charmbracelet/x/vt` v0.1.0 (MIT, active)
|
||||
keeps scroll region, pen and modes private and scrolls by copying cells:
|
||||
measured 0.2-1 MB/s for `seq` and 4.5 MB/s for wrapping text, 33 MB/s for
|
||||
redraws. `github.com/vito/midterm` v0.2.5 (MIT): 1-4 MB/s scrolling,
|
||||
ignores keypad and most modes. `github.com/hinshun/vt10x`: unmaintained
|
||||
since 2022, no scrollback or bracketed paste. termstate moves rows by
|
||||
pointer, keeps blank cells implicit and recycles evicted scrollback rows.
|
||||
|
||||
Measured (`go test ./internal/termstate -bench .`, Ryzen 7 5800X, 8 MB
|
||||
each, 32 KiB writes): `seq` 190 MB/s, coloured full-screen redraws 160-165
|
||||
MB/s, wrapping mixed text 172-180 MB/s, at 80x24 and 200x50; a snapshot of
|
||||
1000 full 200-column scrollback rows: 2 ms, 229 KiB (seq: 9 KiB; a 40-row
|
||||
TUI: 4-39 KiB). Cells: 230 KiB per terminal for `seq`, up to 5.9 MB at
|
||||
200 columns with 1000 full rows. End to end (`TestMeasureTerminalStream`,
|
||||
same machine, two runs each, before → after): seq 20.8/22.8 → 25.0/25.3
|
||||
MB/s, cat 80/102 → 80/76 MB/s, yes 10.4/11.4 → 10.4/10.7 MB/s, echo
|
||||
median 0.36/0.41 → 0.48/0.38 ms: no measurable cost.
|
||||
|
||||
Known gaps: origin mode with the cursor outside the scroll region (a DECRC
|
||||
can leave it there) is not recreated; hyperlinks (OSC 8), palette changes
|
||||
(OSC 4/10/11), DECSLRM and kitty keyboard modes are not tracked; DECSC's
|
||||
origin flag is not saved (as in the app's emulator); scrolled-in rows are
|
||||
blank in the default colour (as in the app's emulator, not xterm's BCE).
|
||||
The server emulates at the PTY size; a client drawing at another size gets
|
||||
the snapshot at the PTY's.
|
||||
|
||||
## Login and lifetime (server)
|
||||
|
||||
- `internal/server/terminal_login.go`. A terminal runs, in its PTY,
|
||||
@@ -339,7 +406,10 @@ longest turn 12.5 ms.
|
||||
|
||||
- Server: `internal/protocol/terminal.go`, `message.go`;
|
||||
`internal/pipeline/terminals.go`, `store.go`;
|
||||
`internal/server/terminal_{manager,supervise,process,login,legacy_tmux,clients,title,cwd,handlers}.go`,
|
||||
`internal/server/terminal_{manager,supervise,process,login,legacy_tmux,clients,title,cwd,handlers,flow,screen}.go`,
|
||||
`internal/termstate/` (headless emulator and snapshots; tests
|
||||
`snapshot_test.go`, `random_test.go`, `bench_test.go`),
|
||||
`terminal_screen_test.go`,
|
||||
`websocket.go`, `cmd/pipelines-server/main.go`; tests `terminal_ws_test.go`,
|
||||
`terminal_login_test.go`, `terminal_lifetime_test.go`, `terminal_legacy_tmux_test.go`,
|
||||
`internal/pipeline/terminals_test.go`; `docs/cli.md`.
|
||||
|
||||
@@ -28,6 +28,12 @@ class TerminalGateway implements ApiGateway {
|
||||
/// where runs of invalid bytes became one shorter replacement character).
|
||||
final Map<String, int> byteShift = {};
|
||||
|
||||
/// A terminal's state as the server's snapshot: when set, a read from
|
||||
/// before [snapshotFrom] gets it (as of the output's end) instead of raw
|
||||
/// output.
|
||||
final Map<String, String> snapshots = {};
|
||||
int snapshotFrom = 1 << 30;
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => _frames.stream;
|
||||
|
||||
@@ -56,6 +62,19 @@ class TerminalGateway implements ApiGateway {
|
||||
final text = output[id] ?? '';
|
||||
final bytes = utf8.encode(text);
|
||||
final start = after.clamp(0, bytes.length);
|
||||
final snapshot = snapshots[id];
|
||||
if (withOutput && snapshot != null && after < snapshotFrom) {
|
||||
final end = bytes.length + (byteShift[id] ?? 0);
|
||||
return {
|
||||
...terminals[id]!,
|
||||
'stream': stream,
|
||||
'output': snapshot,
|
||||
'output_start': end,
|
||||
'output_end': end,
|
||||
'output_snapshot': true,
|
||||
if (window > 0) 'window': window,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...terminals[id]!,
|
||||
'stream': stream,
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_hub.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_tab.dart';
|
||||
import 'package:xterm/core.dart';
|
||||
|
||||
import 'terminal_fixtures.dart';
|
||||
|
||||
/// What the server's emulator (internal/termstate) writes for a 40x8
|
||||
/// terminal where a shell ran twelve commands and then nvim, which set
|
||||
/// mouse, bracketed paste and application cursor/keypad modes on the
|
||||
/// alternate screen.
|
||||
const _snapshot =
|
||||
'\x1bc\x1b[3J\x1b]2;nvim notes.txt\x07'
|
||||
'\$ echo 1\r\n1\r\n\$ echo 2\r\n2\r\n\$ echo 3\r\n3\r\n\$ echo 4\r\n4\r\n'
|
||||
'\$ echo 5\r\n5\r\n\$ echo 6\r\n6\r\n\$ echo 7\r\n7\r\n\$ echo 8\r\n8\r\n'
|
||||
'\$ echo 9\r\n9\r\n\$ echo 10\r\n10\r\n\$ echo 11\r\n11\r\n'
|
||||
'\$ echo 12\r\n12\r\n\$ nvim notes.txt\r\n'
|
||||
'\x1b[8;1H\x1b[?1049h\x1b[1;1H\x1b[0;1;34mFRAME\x1b[2;1H\x1b[0mline two'
|
||||
'\x1b[8;1H\x1b[0;7m-- INSERT --\x1b[2;9H\x1b[?1h\x1b=\x1b[?25l'
|
||||
'\x1b[?1002h\x1b[?1006h\x1b[?2004h\x1b[0m';
|
||||
|
||||
/// What nvim writes as it exits, then the shell.
|
||||
const _exit =
|
||||
'\x1b[?2004l\x1b[?1006l\x1b[?1002l\x1b[?1l\x1b>\x1b[?25h\x1b[?1049l'
|
||||
'\$ ls\r\nnotes.txt\r\n\$ ';
|
||||
|
||||
/// The rows on screen (not the scrollback), trailing blanks trimmed.
|
||||
List<String> rows(Terminal terminal) {
|
||||
final buffer = terminal.buffer;
|
||||
final top = buffer.height - terminal.viewHeight;
|
||||
return [
|
||||
for (var y = top; y < buffer.height; y++)
|
||||
buffer.lines[y].getText().trimRight(),
|
||||
];
|
||||
}
|
||||
|
||||
void main() {
|
||||
late TerminalGateway mac;
|
||||
late TerminalHub hub;
|
||||
|
||||
setUp(() {
|
||||
mac = TerminalGateway()..window = 1 << 18;
|
||||
hub = TerminalHub(TestMachines([machine('mac', mac, name: 'Mac')]));
|
||||
});
|
||||
tearDown(() async {
|
||||
hub.dispose();
|
||||
await mac.close();
|
||||
});
|
||||
|
||||
Future<void> settle() async {
|
||||
for (var i = 0; i < 5; i++) {
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}
|
||||
}
|
||||
|
||||
/// A terminal whose stream is longer than the server's tail.
|
||||
void longTerminal(String raw) {
|
||||
mac.add('term_a', text: raw);
|
||||
mac.terminals['term_a']!['cols'] = 40;
|
||||
mac.terminals['term_a']!['rows'] = 8;
|
||||
}
|
||||
|
||||
void expectNvim(TerminalTab tab) {
|
||||
final terminal = tab.session.terminal;
|
||||
expect(terminal.isUsingAltBuffer, isTrue);
|
||||
expect(rows(terminal), [
|
||||
'FRAME',
|
||||
'line two',
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
'-- INSERT --',
|
||||
]);
|
||||
expect(terminal.buffer.cursorX, 8);
|
||||
expect(terminal.buffer.cursorY, 1);
|
||||
expect(terminal.mouseMode, MouseMode.upDownScrollDrag);
|
||||
expect(terminal.mouseReportMode, MouseReportMode.sgr);
|
||||
expect(terminal.bracketedPasteMode, isTrue);
|
||||
expect(terminal.cursorKeysMode, isTrue);
|
||||
expect(terminal.appKeypadMode, isTrue);
|
||||
expect(terminal.cursorVisibleMode, isFalse);
|
||||
expect(tab.title, 'nvim notes.txt');
|
||||
}
|
||||
|
||||
void expectShellAfterExit(TerminalTab tab) {
|
||||
final terminal = tab.session.terminal;
|
||||
expect(terminal.isUsingAltBuffer, isFalse);
|
||||
expect(rows(terminal), [
|
||||
r'$ echo 11',
|
||||
'11',
|
||||
r'$ echo 12',
|
||||
'12',
|
||||
r'$ nvim notes.txt',
|
||||
r'$ ls',
|
||||
'notes.txt',
|
||||
r'$',
|
||||
]);
|
||||
// The shell's history above the screen came back with it.
|
||||
expect(terminal.buffer.lines[0].getText().trimRight(), r'$ echo 1');
|
||||
expect(terminal.mouseMode, MouseMode.none);
|
||||
expect(terminal.bracketedPasteMode, isFalse);
|
||||
expect(terminal.cursorKeysMode, isFalse);
|
||||
expect(terminal.cursorVisibleMode, isTrue);
|
||||
}
|
||||
|
||||
test('a reload draws the snapshot: the program on the alternate screen, '
|
||||
'its modes, and the shell underneath once it exits', () async {
|
||||
longTerminal('x' * 3000);
|
||||
mac.snapshots['term_a'] = _snapshot;
|
||||
hub.activate();
|
||||
await settle();
|
||||
final tab = hub.tabs.single;
|
||||
expect(mac.bodies('terminal_output').single['after'], isNull);
|
||||
expect(tab.session.end, 3000);
|
||||
expectNvim(tab);
|
||||
// No "earlier output was dropped" line: the snapshot misses nothing.
|
||||
expect(
|
||||
tab.session.terminal.mainBuffer.lines[0].getText(),
|
||||
isNot(contains('dropped')),
|
||||
);
|
||||
mac.write('term_a', _exit);
|
||||
await settle();
|
||||
expectShellAfterExit(tab);
|
||||
});
|
||||
|
||||
test('after a gap the snapshot replaces what the tab drew, modes '
|
||||
'included', () async {
|
||||
longTerminal('stale\x1b[?1000h\x1b[?1049h');
|
||||
hub.activate();
|
||||
await settle();
|
||||
final tab = hub.tabs.single;
|
||||
expect(tab.session.terminal.mouseMode, MouseMode.upDownScroll);
|
||||
final held = tab.session.end;
|
||||
// The tab falls behind past the server's tail, which now starts later.
|
||||
mac.write('term_a', 'y' * 5000, push: false);
|
||||
mac.snapshots['term_a'] = _snapshot;
|
||||
mac.snapshotFrom = held + 100;
|
||||
final end = held + 5000;
|
||||
mac.pushOutput('term_a', 'z', end, end: end + 1);
|
||||
await settle();
|
||||
expect(mac.bodies('terminal_output').last['after'], held);
|
||||
expectNvim(tab);
|
||||
mac.write('term_a', _exit);
|
||||
await settle();
|
||||
expectShellAfterExit(tab);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user