//! Transcript items as vxfw widgets. One widget per model item, built on demand //! for the rows the ListView draws. const std = @import("std"); const vaxis = @import("vaxis"); const vxfw = vaxis.vxfw; const block = @import("block.zig"); const transcripts = @import("../transcript.zig"); const view_tool = @import("tool.zig"); const testing = std.testing; const cellAt = @import("testing.zig").cellAt; const styles = struct { const user: vaxis.Style = .{ .bg = .{ .index = 8 } }; const assistant: vaxis.Style = .{}; const thinking: vaxis.Style = .{ .italic = true }; const err: vaxis.Style = .{ .fg = .{ .index = 1 } }; const notice: vaxis.Style = .{ .fg = .{ .index = 3 } }; const info: vaxis.Style = .{ .dim = true }; const tool_running: vaxis.Style = .{ .bg = .{ .index = 8 } }; const tool_success: vaxis.Style = .{ .bg = .{ .index = 2 } }; const tool_error: vaxis.Style = .{ .bg = .{ .index = 1 } }; }; /// Builds one widget per transcript item for a ListView. pub const Builder = struct { transcript: *transcripts.Transcript, arena: std.mem.Allocator, cache: ?*Cache = null, pub fn source(self: *const Builder) vxfw.ListView.Source { return .{ .builder = .{ .userdata = self, .buildFn = build } }; } fn build(ptr: *const anyopaque, index: usize, _: usize) ?vxfw.Widget { const self: *const Builder = @ptrCast(@alignCast(ptr)); if (index >= self.transcript.items.items.len) { return null; } const item = self.arena.create(Item) catch return null; item.* = .{ .transcript = self.transcript, .index = index, .separator = index > 0, .cache = self.cache }; return item.widget(); } }; /// The surfaces of drawn items, kept across frames so that an item that did /// not change is not laid out again. pub const Cache = struct { gpa: std.mem.Allocator, entries: std.ArrayList(Entry) = .empty, /// The width method of the screen the items are drawn for. width_method: vaxis.gwidth.Method = .wcwidth, const Entry = struct { index: usize, /// Null until a layout succeeds. key: ?Key, arena: std.heap.ArenaAllocator, surface: vxfw.Surface, used: bool, }; /// The text slices identify the content: a change moves or grows them. const Key = struct { width: u16, width_method: vaxis.gwidth.Method, texts: [3][]const u8 = @splat(""), open: bool = false, state: transcripts.State = .ok, fn of(item: transcripts.Transcript.Item, show_thinking: bool, width: u16, width_method: vaxis.gwidth.Method) Key { var key: Key = .{ .width = width, .width_method = width_method }; switch (item) { .user => |text| key.texts[0] = text, .assistant => |text| key.texts[0] = text.items, .thinking => |text| { key.texts[0] = text.items; key.open = show_thinking; }, .notice => |notice| key.texts[0] = notice.text, .tool => |tool| { key.texts = .{ tool.call.text, tool.collapsed.text, tool.expanded.text }; key.open = tool.open; key.state = tool.state; }, } return key; } }; pub fn init(gpa: std.mem.Allocator) Cache { return .{ .gpa = gpa }; } pub fn deinit(self: *Cache) void { for (self.entries.items) |entry| entry.arena.deinit(); self.entries.deinit(self.gpa); } /// Frees the surfaces of the items that were not drawn since the last sweep. pub fn sweep(self: *Cache) void { var index: usize = 0; while (index < self.entries.items.len) { const entry = &self.entries.items[index]; if (entry.used) { entry.used = false; index += 1; } else { entry.arena.deinit(); _ = self.entries.swapRemove(index); } } } fn draw(self: *Cache, item: *const Item, ctx: vxfw.DrawContext, width: u16) std.mem.Allocator.Error!vxfw.Surface { const key: Key = .of(item.item(), item.transcript.show_thinking, width, self.width_method); const entry = for (self.entries.items) |*entry| { if (entry.index != item.index) { continue; } if (entry.key != null and std.meta.eql(entry.key.?, key)) { entry.used = true; return entry.surface; } _ = entry.arena.reset(.retain_capacity); break entry; } else blk: { try self.entries.append(self.gpa, .{ .index = item.index, .key = null, .arena = .init(self.gpa), .surface = undefined, .used = false }); break :blk &self.entries.items[self.entries.items.len - 1]; }; entry.key = null; var entry_ctx = ctx; entry_ctx.arena = entry.arena.allocator(); // The surface outlives this frame's widgets, so it points at its own copy. const owned = try entry_ctx.arena.create(Item); owned.* = item.*; entry.surface = try owned.layout(entry_ctx, width); entry.key = key; entry.used = true; return entry.surface; } }; /// One item, with the blank row that separates it from the item above. It holds /// its place in the transcript, not a copy, so a click can change the item. const Item = struct { transcript: *transcripts.Transcript, index: usize, separator: bool, cache: ?*Cache = null, fn item(self: *const Item) transcripts.Transcript.Item { return self.transcript.items.items[self.index]; } pub fn widget(self: *const Item) vxfw.Widget { return .{ .userdata = @constCast(self), .drawFn = typeErasedDrawFn, .eventHandler = typeErasedEventHandler, }; } fn typeErasedEventHandler(ptr: *anyopaque, ctx: *vxfw.EventContext, event: vxfw.Event) anyerror!void { const self: *Item = @ptrCast(@alignCast(ptr)); switch (event) { .mouse => |mouse| { // Only a left press toggles, so a release, a drag or a side wheel // does not flip the block twice. if (mouse.type != .press or mouse.button != .left) { return; } self.transcript.toggleItem(self.index); ctx.consumeAndRedraw(); }, else => {}, } } fn typeErasedDrawFn(ptr: *anyopaque, ctx: vxfw.DrawContext) std.mem.Allocator.Error!vxfw.Surface { const self: *const Item = @ptrCast(@alignCast(ptr)); return self.draw(ctx); } pub fn draw(self: *const Item, ctx: vxfw.DrawContext) std.mem.Allocator.Error!vxfw.Surface { const width = ctx.max.width orelse return vxfw.Surface.empty(self.widget()); if (self.cache) |cache| { return cache.draw(self, ctx, width); } return self.layout(ctx, width); } fn layout(self: *const Item, ctx: vxfw.DrawContext, width: u16) std.mem.Allocator.Error!vxfw.Surface { const content = try contentWidget(self.item(), self.transcript.show_thinking, ctx.arena) orelse return vxfw.Surface.empty(self.widget()); const surface = try content.draw(ctx.withConstraints( .{ .width = width, .height = 0 }, .{ .width = width, .height = null }, )); // A hidden item adds no separator row of its own. const top: u16 = @intFromBool(self.separator and surface.size.height > 0); const children = try ctx.arena.alloc(vxfw.SubSurface, 1); children[0] = .{ .origin = .{ .row = top, .col = 0 }, .surface = surface }; return .{ .size = .{ .width = width, .height = surface.size.height + top }, .widget = self.widget(), .buffer = &.{}, .children = children, }; } }; fn contentWidget(item: transcripts.Transcript.Item, show_thinking: bool, arena: std.mem.Allocator) std.mem.Allocator.Error!?vxfw.Widget { switch (item) { .user => |text| { const padded = try arena.create(block.Block); padded.* = .{ .style = styles.user, .child = try textWidget(arena, text, styles.user, true) }; return padded.widget(); }, .assistant => |text| return try textWidget(arena, text.items, styles.assistant, true), .thinking => |text| return try textWidget(arena, if (show_thinking) text.items else "Thinking...", styles.thinking, true), .notice => |notice| { const style: vaxis.Style = switch (notice.kind) { .err => styles.err, .interrupted => styles.notice, .info => styles.info, }; return try textWidget(arena, std.mem.sliceTo(notice.text, '\n'), style, false); }, .tool => |tool| { const style = switch (tool.state) { .running => styles.tool_running, .ok => styles.tool_success, .failed => styles.tool_error, }; var parts: std.ArrayList(vxfw.Widget) = .empty; if (try view_tool.layout(arena, tool.call, style)) |call| { try parts.append(arena, call); } if (try view_tool.layout(arena, if (tool.open) tool.expanded else tool.collapsed, style)) |result| { try parts.append(arena, result); } if (parts.items.len == 0) { return null; } const column = try arena.create(view_tool.Column); column.* = .{ .children = parts.items }; const padded = try arena.create(block.Block); padded.* = .{ .style = style, .child = column.widget() }; return padded.widget(); }, } } fn textWidget(arena: std.mem.Allocator, text: []const u8, style: vaxis.Style, softwrap: bool) std.mem.Allocator.Error!vxfw.Widget { const segments = try arena.dupe(vaxis.Segment, &.{.{ .text = text, .style = style }}); return view_tool.text(arena, segments, style, softwrap); } fn context(arena: std.mem.Allocator, width: u16) vxfw.DrawContext { return .{ .arena = arena, .min = .{}, .max = .{ .width = width, .height = null }, .cell_size = .{}, }; } test "items after the first start with a blank separator row" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); vxfw.DrawContext.init(.wcwidth); var transcript = transcripts.Transcript.init(testing.allocator); defer transcript.deinit(); try transcript.items.append(testing.allocator, .{ .assistant = .fromOwnedSlice(try testing.allocator.dupe(u8, "one")) }); try transcript.items.append(testing.allocator, .{ .assistant = .fromOwnedSlice(try testing.allocator.dupe(u8, "two")) }); const builder: Builder = .{ .transcript = &transcript, .arena = arena }; const source = builder.source(); const first = source.builder.buildFn(source.builder.userdata, 0, 0).?; const second = source.builder.buildFn(source.builder.userdata, 1, 0).?; try testing.expect(source.builder.buildFn(source.builder.userdata, 2, 0) == null); const first_surface = try first.draw(context(arena, 10)); const second_surface = try second.draw(context(arena, 10)); try testing.expectEqual(@as(u16, 1), first_surface.size.height); try testing.expectEqual(@as(u16, 2), second_surface.size.height); try testing.expectEqual(@as(i17, 1), second_surface.children[0].origin.row); } test "a tool block pads its call line and its result" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); vxfw.DrawContext.init(.wcwidth); var owned = transcripts.Transcript.init(testing.allocator); defer owned.deinit(); try owned.items.append(testing.allocator, .{ .tool = .{ .id = try testing.allocator.dupe(u8, "call"), .state = .ok, .call = try .init(testing.allocator, &.{ .{ .text = "bash", .style = .{ .bold = true } }, .{ .text = " echo hi" } }), .collapsed = try .init(testing.allocator, &.{.{ .text = "exit 0, 1.23s" }}), .expanded = try .init(testing.allocator, &.{.{ .text = "hi\n[exit code 0, elapsed 1.23s]" }}), } }); const widget = try arena.create(Item); widget.* = .{ .transcript = &owned, .index = 0, .separator = false }; const surface = try widget.widget().draw(context(arena, 40)); // One padding row, the call line, the collapsed result and one padding row. try testing.expectEqual(@as(u16, 4), surface.size.height); try testing.expectEqual(@as(u8, 2), cellAt(surface, 0, 0).?.style.bg.index); try testing.expect(cellAt(surface, 1, 1).?.style.bold); try testing.expectEqualStrings("b", cellAt(surface, 1, 1).?.char.grapheme); try testing.expectEqualStrings("e", cellAt(surface, 1, 2).?.char.grapheme); } test "a cached item is laid out again only when it changes" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); vxfw.DrawContext.init(.wcwidth); var owned = transcripts.Transcript.init(testing.allocator); defer owned.deinit(); try owned.items.append(testing.allocator, .{ .assistant = .fromOwnedSlice(try testing.allocator.dupe(u8, "one")) }); try owned.items.append(testing.allocator, .{ .tool = .{ .id = try testing.allocator.dupe(u8, "call"), .state = .ok, .call = try .init(testing.allocator, &.{.{ .text = "bash" }}), .collapsed = try .init(testing.allocator, &.{.{ .text = "exit 0" }}), .expanded = try .init(testing.allocator, &.{.{ .text = "out" }}), } }); var cache: Cache = .init(testing.allocator); defer cache.deinit(); const reply: Item = .{ .transcript = &owned, .index = 0, .separator = false, .cache = &cache }; const tool: Item = .{ .transcript = &owned, .index = 1, .separator = true, .cache = &cache }; const first = try reply.widget().draw(context(arena, 10)); try testing.expectEqual(first.children.ptr, (try reply.widget().draw(context(arena, 10))).children.ptr); try owned.items.items[0].assistant.appendSlice(testing.allocator, " two"); try testing.expectEqualStrings("t", cellAt(try reply.widget().draw(context(arena, 10)), 4, 0).?.char.grapheme); try testing.expectEqualStrings("t", cellAt(try reply.widget().draw(context(arena, 4)), 0, 1).?.char.grapheme); // Rows: the separator, padding, the call line, the result and padding. try testing.expectEqualStrings("e", cellAt(try tool.widget().draw(context(arena, 20)), 1, 3).?.char.grapheme); owned.toggleItem(1); try testing.expectEqualStrings("o", cellAt(try tool.widget().draw(context(arena, 20)), 1, 3).?.char.grapheme); cache.sweep(); try testing.expectEqual(@as(usize, 2), cache.entries.items.len); cache.sweep(); try testing.expectEqual(@as(usize, 0), cache.entries.items.len); } test "hidden thinking is one italic label, and comes back when shown" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); vxfw.DrawContext.init(.wcwidth); var owned = transcripts.Transcript.init(testing.allocator); defer owned.deinit(); owned.apply(.{ .thinking_delta = try testing.allocator.dupe(u8, "first line\nsecond line") }); var cache: Cache = .init(testing.allocator); defer cache.deinit(); const item: Item = .{ .transcript = &owned, .index = 0, .separator = false, .cache = &cache }; try testing.expectEqual(@as(u16, 2), (try item.widget().draw(context(arena, 20))).size.height); owned.toggleThinking(); const hidden = try item.widget().draw(context(arena, 20)); try testing.expectEqual(@as(u16, 1), hidden.size.height); var label: std.ArrayList(u8) = .empty; for (0.."Thinking...".len) |col| { const cell = cellAt(hidden, @intCast(col), 0).?; try testing.expect(cell.style.italic); try label.appendSlice(arena, cell.char.grapheme); } try testing.expectEqualStrings("Thinking...", label.items); owned.toggleThinking(); const shown = try item.widget().draw(context(arena, 20)); try testing.expectEqual(@as(u16, 2), shown.size.height); try testing.expectEqualStrings("f", cellAt(shown, 0, 0).?.char.grapheme); } test "a notice that only informs is dim" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); vxfw.DrawContext.init(.wcwidth); var owned = transcripts.Transcript.init(testing.allocator); defer owned.deinit(); try owned.items.append(testing.allocator, .{ .notice = .{ .kind = .info, .text = try testing.allocator.dupe(u8, "kimi") }, }); const item: Item = .{ .transcript = &owned, .index = 0, .separator = false }; const cell = cellAt(try item.widget().draw(context(arena, 10)), 0, 0).?; try testing.expect(cell.style.dim); try testing.expectEqual(vaxis.Color.default, cell.style.fg); } test "a notice stays on one line" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); vxfw.DrawContext.init(.wcwidth); var owned = transcripts.Transcript.init(testing.allocator); defer owned.deinit(); try owned.items.append(testing.allocator, .{ .notice = .{ .kind = .err, .text = try testing.allocator.dupe(u8, "a long message\nsecond line") }, }); const widget = try arena.create(Item); widget.* = .{ .transcript = &owned, .index = 0, .separator = false }; const surface = try widget.widget().draw(context(arena, 10)); try testing.expectEqual(@as(u16, 1), surface.size.height); const text = surface.children[0].surface; try testing.expectEqual(@as(u16, 1), text.size.height); try testing.expectEqual(@as(u8, 1), text.readCell(0, 0).style.fg.index); } test "a long reply and an expanded long tool result draw every line" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); vxfw.DrawContext.init(.wcwidth); var text: std.ArrayList(u8) = .empty; for (0..999) |_| try text.appendSlice(arena, "a\n"); try text.appendSlice(arena, "z"); var owned = transcripts.Transcript.init(testing.allocator); defer owned.deinit(); try owned.items.append(testing.allocator, .{ .assistant = .fromOwnedSlice(try testing.allocator.dupe(u8, text.items)) }); try owned.items.append(testing.allocator, .{ .tool = .{ .id = try testing.allocator.dupe(u8, "call"), .state = .ok, .open = true, .call = try .init(testing.allocator, &.{.{ .text = "bash" }}), .collapsed = try .init(testing.allocator, &.{.{ .text = "exit 0" }}), .expanded = try .init(testing.allocator, &.{ .{ .text = text.items[0..1000] }, .{ .text = text.items[1000..] } }), } }); const reply = try arena.create(Item); reply.* = .{ .transcript = &owned, .index = 0, .separator = false }; const reply_surface = try reply.widget().draw(context(arena, 300)); try testing.expectEqual(@as(u16, 1000), reply_surface.size.height); try testing.expectEqualStrings("z", cellAt(reply_surface, 0, 999).?.char.grapheme); const tool = try arena.create(Item); tool.* = .{ .transcript = &owned, .index = 1, .separator = false }; const tool_surface = try tool.widget().draw(context(arena, 300)); // One padding row, the call line, the result and one padding row. try testing.expectEqual(@as(u16, 1003), tool_surface.size.height); try testing.expectEqualStrings("z", cellAt(tool_surface, 1, 1001).?.char.grapheme); try testing.expectEqual(@as(u8, 2), cellAt(tool_surface, 299, 1001).?.style.bg.index); } test "a long line without newlines draws every character" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); vxfw.DrawContext.init(.wcwidth); var owned = transcripts.Transcript.init(testing.allocator); defer owned.deinit(); for ([_][]const u8{ "x", "€" }) |char| { var text: std.ArrayList(u8) = .empty; for (0..100_000) |_| try text.appendSlice(arena, char); try owned.items.append(testing.allocator, .{ .assistant = .fromOwnedSlice(try testing.allocator.dupe(u8, text.items)) }); } for ([_][]const u8{ "x", "€" }, 0..) |char, index| { const reply = try arena.create(Item); reply.* = .{ .transcript = &owned, .index = index, .separator = false }; const surface = try reply.widget().draw(context(arena, 300)); var count: usize = 0; for (0..surface.size.height) |row| for (0..300) |col| { const grapheme = cellAt(surface, @intCast(col), @intCast(row)).?.char.grapheme; if (std.mem.eql(u8, grapheme, char)) { count += 1; } else { try testing.expectEqualStrings(" ", grapheme); } }; try testing.expectEqual(@as(usize, 100_000), count); } } test "lines that cross a chunk boundary stay whole" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); vxfw.DrawContext.init(.wcwidth); var text: std.ArrayList(u8) = .empty; for (0..100) |_| { try text.appendNTimes(arena, 'x', 299); try text.append(arena, '\n'); } var owned = transcripts.Transcript.init(testing.allocator); defer owned.deinit(); try owned.items.append(testing.allocator, .{ .assistant = .fromOwnedSlice(try testing.allocator.dupe(u8, text.items)) }); const reply = try arena.create(Item); reply.* = .{ .transcript = &owned, .index = 0, .separator = false }; try testing.expectEqual(@as(u16, 100), (try reply.widget().draw(context(arena, 300))).size.height); } test "an item taller than the row limit is cut at the limit" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); vxfw.DrawContext.init(.wcwidth); var text: std.ArrayList(u8) = .empty; for (0..70_000) |_| try text.appendSlice(arena, "a\n"); var owned = transcripts.Transcript.init(testing.allocator); defer owned.deinit(); try owned.items.append(testing.allocator, .{ .assistant = .fromOwnedSlice(try testing.allocator.dupe(u8, "one")) }); try owned.items.append(testing.allocator, .{ .user = try testing.allocator.dupe(u8, text.items) }); const prompt = try arena.create(Item); prompt.* = .{ .transcript = &owned, .index = 1, .separator = true }; const surface = try prompt.widget().draw(context(arena, 4)); try testing.expectEqual(@as(u16, std.math.maxInt(u16)), surface.size.height); }