feat(harness): create the setup PTY at the browser's size

The setup terminal created its PTY at a fixed 24x80 while the browser
measured its own box and threw the measurement away, so a full-screen CLI
login drew into a corner of a much larger xterm.

OpenRequest now carries a ConsoleSize with the target frame; the route
reads cols/rows from the WebSocket URL, falling back to 24x80 when they
are absent or out of range, and the daemon creates the PTY at that
geometry. The component sends the size it measured before connecting.

Live resize is the follow-on: it needs a control channel on the WebSocket,
which today is a raw byte copy.
This commit is contained in:
sam committed 2026-10-09 13:07:29 +11:00
1 parent 96dde2ec88
commit b395c17066
10 files changed
+204 -50

No files matched your search

+3 -3
View File
@@ -88,7 +88,7 @@ func (h *harnessServer) Open(stream pb.HarnessService_OpenServer) error {
if t.Setup.GetProfile() == "" { if t.Setup.GetProfile() == "" {
return status.Error(codes.InvalidArgument, "the setup target names no profile") return status.Error(codes.InvalidArgument, "the setup target names no profile")
} }
return h.openSetup(stream, target.GetOrg(), t.Setup.GetProfile()) return h.openSetup(stream, target.GetOrg(), t.Setup.GetProfile(), first.GetSize())
case *pb.OpenTarget_Run: case *pb.OpenTarget_Run:
return status.Error(codes.Unimplemented, "run-scoped sessions are not served yet") return status.Error(codes.Unimplemented, "run-scoped sessions are not served yet")
default: default:
@@ -98,8 +98,8 @@ func (h *harnessServer) Open(stream pb.HarnessService_OpenServer) error {
// openSetup opens one setup session and pumps frames until the shell exits or // openSetup opens one setup session and pumps frames until the shell exits or
// either side closes. Teardown runs on every return. // either side closes. Teardown runs on every return.
func (h *harnessServer) openSetup(stream pb.HarnessService_OpenServer, org, profile string) error { func (h *harnessServer) openSetup(stream pb.HarnessService_OpenServer, org, profile string, size *pb.ConsoleSize) error {
session, err := h.sessions.Open(stream.Context(), org, profile) session, err := h.sessions.Open(stream.Context(), org, profile, int(size.GetRows()), int(size.GetCols()))
if err != nil { if err != nil {
h.log.Warn("setup session failed to open", "org", org, "profile", profile, "err", err) h.log.Warn("setup session failed to open", "org", org, "profile", profile, "err", err)
// The failure rides the stream as a frame, not only as a status: the // The failure rides the stream as a frame, not only as a status: the
+85 -15
View File
@@ -29,7 +29,11 @@ type OpenRequest struct {
// //
// *OpenRequest_Target // *OpenRequest_Target
// *OpenRequest_Stdin // *OpenRequest_Stdin
Frame isOpenRequest_Frame `protobuf_oneof:"frame"` Frame isOpenRequest_Frame `protobuf_oneof:"frame"`
// size is the terminal size the client wants, in character cells. The
// dashboard sends it with the target frame so the PTY is created at the
// right size; the daemon falls back to its own default when it is absent.
Size *ConsoleSize `protobuf:"bytes,3,opt,name=size,proto3" json:"size,omitempty"`
unknownFields protoimpl.UnknownFields unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache sizeCache protoimpl.SizeCache
} }
@@ -89,6 +93,13 @@ func (x *OpenRequest) GetStdin() []byte {
return nil return nil
} }
func (x *OpenRequest) GetSize() *ConsoleSize {
if x != nil {
return x.Size
}
return nil
}
type isOpenRequest_Frame interface { type isOpenRequest_Frame interface {
isOpenRequest_Frame() isOpenRequest_Frame()
} }
@@ -402,15 +413,69 @@ func (x *RunTarget) GetAttempt() int64 {
return 0 return 0
} }
// ConsoleSize is a terminal size in character cells.
type ConsoleSize struct {
state protoimpl.MessageState `protogen:"open.v1"`
Rows uint32 `protobuf:"varint,1,opt,name=rows,proto3" json:"rows,omitempty"`
Cols uint32 `protobuf:"varint,2,opt,name=cols,proto3" json:"cols,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ConsoleSize) Reset() {
*x = ConsoleSize{}
mi := &file_harness_v1_harness_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ConsoleSize) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ConsoleSize) ProtoMessage() {}
func (x *ConsoleSize) ProtoReflect() protoreflect.Message {
mi := &file_harness_v1_harness_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ConsoleSize.ProtoReflect.Descriptor instead.
func (*ConsoleSize) Descriptor() ([]byte, []int) {
return file_harness_v1_harness_proto_rawDescGZIP(), []int{5}
}
func (x *ConsoleSize) GetRows() uint32 {
if x != nil {
return x.Rows
}
return 0
}
func (x *ConsoleSize) GetCols() uint32 {
if x != nil {
return x.Cols
}
return 0
}
var File_harness_v1_harness_proto protoreflect.FileDescriptor var File_harness_v1_harness_proto protoreflect.FileDescriptor
const file_harness_v1_harness_proto_rawDesc = "" + const file_harness_v1_harness_proto_rawDesc = "" +
"\n" + "\n" +
"\x18harness/v1/harness.proto\x12\n" + "\x18harness/v1/harness.proto\x12\n" +
"harness.v1\"`\n" + "harness.v1\"\x8d\x01\n" +
"\vOpenRequest\x120\n" + "\vOpenRequest\x120\n" +
"\x06target\x18\x01 \x01(\v2\x16.harness.v1.OpenTargetH\x00R\x06target\x12\x16\n" + "\x06target\x18\x01 \x01(\v2\x16.harness.v1.OpenTargetH\x00R\x06target\x12\x16\n" +
"\x05stdin\x18\x02 \x01(\fH\x00R\x05stdinB\a\n" + "\x05stdin\x18\x02 \x01(\fH\x00R\x05stdin\x12+\n" +
"\x04size\x18\x03 \x01(\v2\x17.harness.v1.ConsoleSizeR\x04sizeB\a\n" +
"\x05frame\"h\n" + "\x05frame\"h\n" +
"\fOpenResponse\x12\x18\n" + "\fOpenResponse\x12\x18\n" +
"\x06stdout\x18\x01 \x01(\fH\x00R\x06stdout\x12\x1d\n" + "\x06stdout\x18\x01 \x01(\fH\x00R\x06stdout\x12\x1d\n" +
@@ -427,7 +492,10 @@ const file_harness_v1_harness_proto_rawDesc = "" +
"\aprofile\x18\x01 \x01(\tR\aprofile\">\n" + "\aprofile\x18\x01 \x01(\tR\aprofile\">\n" +
"\tRunTarget\x12\x17\n" + "\tRunTarget\x12\x17\n" +
"\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x18\n" + "\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x18\n" +
"\aattempt\x18\x02 \x01(\x03R\aattempt2O\n" + "\aattempt\x18\x02 \x01(\x03R\aattempt\"5\n" +
"\vConsoleSize\x12\x12\n" +
"\x04rows\x18\x01 \x01(\rR\x04rows\x12\x12\n" +
"\x04cols\x18\x02 \x01(\rR\x04cols2O\n" +
"\x0eHarnessService\x12=\n" + "\x0eHarnessService\x12=\n" +
"\x04Open\x12\x17.harness.v1.OpenRequest\x1a\x18.harness.v1.OpenResponse(\x010\x01B\xb4\x01\n" + "\x04Open\x12\x17.harness.v1.OpenRequest\x1a\x18.harness.v1.OpenResponse(\x010\x01B\xb4\x01\n" +
"\x0ecom.harness.v1B\fHarnessProtoP\x01ZKgithub.com/samcharles93/archie-core/internal/contracts/harness/v1;harnessv1\xa2\x02\x03HXX\xaa\x02\n" + "\x0ecom.harness.v1B\fHarnessProtoP\x01ZKgithub.com/samcharles93/archie-core/internal/contracts/harness/v1;harnessv1\xa2\x02\x03HXX\xaa\x02\n" +
@@ -446,25 +514,27 @@ func file_harness_v1_harness_proto_rawDescGZIP() []byte {
return file_harness_v1_harness_proto_rawDescData return file_harness_v1_harness_proto_rawDescData
} }
var file_harness_v1_harness_proto_msgTypes = make([]protoimpl.MessageInfo, 5) var file_harness_v1_harness_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
var file_harness_v1_harness_proto_goTypes = []any{ var file_harness_v1_harness_proto_goTypes = []any{
(*OpenRequest)(nil), // 0: harness.v1.OpenRequest (*OpenRequest)(nil), // 0: harness.v1.OpenRequest
(*OpenResponse)(nil), // 1: harness.v1.OpenResponse (*OpenResponse)(nil), // 1: harness.v1.OpenResponse
(*OpenTarget)(nil), // 2: harness.v1.OpenTarget (*OpenTarget)(nil), // 2: harness.v1.OpenTarget
(*SetupTarget)(nil), // 3: harness.v1.SetupTarget (*SetupTarget)(nil), // 3: harness.v1.SetupTarget
(*RunTarget)(nil), // 4: harness.v1.RunTarget (*RunTarget)(nil), // 4: harness.v1.RunTarget
(*ConsoleSize)(nil), // 5: harness.v1.ConsoleSize
} }
var file_harness_v1_harness_proto_depIdxs = []int32{ var file_harness_v1_harness_proto_depIdxs = []int32{
2, // 0: harness.v1.OpenRequest.target:type_name -> harness.v1.OpenTarget 2, // 0: harness.v1.OpenRequest.target:type_name -> harness.v1.OpenTarget
3, // 1: harness.v1.OpenTarget.setup:type_name -> harness.v1.SetupTarget 5, // 1: harness.v1.OpenRequest.size:type_name -> harness.v1.ConsoleSize
4, // 2: harness.v1.OpenTarget.run:type_name -> harness.v1.RunTarget 3, // 2: harness.v1.OpenTarget.setup:type_name -> harness.v1.SetupTarget
0, // 3: harness.v1.HarnessService.Open:input_type -> harness.v1.OpenRequest 4, // 3: harness.v1.OpenTarget.run:type_name -> harness.v1.RunTarget
1, // 4: harness.v1.HarnessService.Open:output_type -> harness.v1.OpenResponse 0, // 4: harness.v1.HarnessService.Open:input_type -> harness.v1.OpenRequest
4, // [4:5] is the sub-list for method output_type 1, // 5: harness.v1.HarnessService.Open:output_type -> harness.v1.OpenResponse
3, // [3:4] is the sub-list for method input_type 5, // [5:6] is the sub-list for method output_type
3, // [3:3] is the sub-list for extension type_name 4, // [4:5] is the sub-list for method input_type
3, // [3:3] is the sub-list for extension extendee 4, // [4:4] is the sub-list for extension type_name
0, // [0:3] is the sub-list for field type_name 4, // [4:4] is the sub-list for extension extendee
0, // [0:4] is the sub-list for field type_name
} }
func init() { file_harness_v1_harness_proto_init() } func init() { file_harness_v1_harness_proto_init() }
@@ -491,7 +561,7 @@ func file_harness_v1_harness_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(), GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_harness_v1_harness_proto_rawDesc), len(file_harness_v1_harness_proto_rawDesc)), RawDescriptor: unsafe.Slice(unsafe.StringData(file_harness_v1_harness_proto_rawDesc), len(file_harness_v1_harness_proto_rawDesc)),
NumEnums: 0, NumEnums: 0,
NumMessages: 5, NumMessages: 6,
NumExtensions: 0, NumExtensions: 0,
NumServices: 1, NumServices: 1,
}, },
@@ -57,21 +57,26 @@ func Dial(target, token string, options ...grpc.DialOption) (*Client, func(), er
return &Client{svc: pb.NewHarnessServiceClient(conn)}, func() { _ = conn.Close() }, nil return &Client{svc: pb.NewHarnessServiceClient(conn)}, func() { _ = conn.Close() }, nil
} }
// Open starts a setup session for profile and returns its duplex stream. The // Open starts a setup session for profile at the requested terminal size and
// returned session satisfies the dashboard's HarnessTerminal interface. A // returns its duplex stream. The returned session satisfies the dashboard's
// failure the server reports before any output arrives is returned here; a // HarnessTerminal interface. A failure the server reports before any output
// failure after the session is open surfaces on Read. // arrives is returned here; a failure after the session is open surfaces on
func (c *Client) Open(ctx context.Context, orgID, profile string) (io.ReadWriteCloser, error) { // Read.
func (c *Client) Open(ctx context.Context, orgID, profile string, rows, cols int) (io.ReadWriteCloser, error) {
streamCtx, cancel := context.WithCancel(ctx) streamCtx, cancel := context.WithCancel(ctx)
stream, err := c.svc.Open(streamCtx) stream, err := c.svc.Open(streamCtx)
if err != nil { if err != nil {
cancel() cancel()
return nil, err return nil, err
} }
target := &pb.OpenRequest{Frame: &pb.OpenRequest_Target{Target: &pb.OpenTarget{ target := &pb.OpenRequest{
Org: orgID, Frame: &pb.OpenRequest_Target{Target: &pb.OpenTarget{
Target: &pb.OpenTarget_Setup{Setup: &pb.SetupTarget{Profile: profile}}, Org: orgID,
}}} Target: &pb.OpenTarget_Setup{Setup: &pb.SetupTarget{Profile: profile}},
}},
// The daemon clamps this; zero means "use your default".
Size: &pb.ConsoleSize{Rows: uint32(max(rows, 0)), Cols: uint32(max(cols, 0))},
}
if err := stream.Send(target); err != nil { if err := stream.Send(target); err != nil {
cancel() cancel()
return nil, err return nil, err
@@ -49,8 +49,18 @@ type Manager struct {
TTL time.Duration TTL time.Duration
} }
// Open starts a setup session and returns its duplex PTY. // Terminal geometry: the fallback when the client asks for no size, and the
func (m *Manager) Open(ctx context.Context, org, profile string) (*Session, error) { // largest the PTY is created with.
const (
terminalDefaultRows = 24
terminalDefaultCols = 80
terminalMaxCells = 1000
)
// Open starts a setup session at the requested terminal size, in character
// cells, and returns its duplex PTY. A zero or out-of-range size falls back to
// the default rather than failing the open.
func (m *Manager) Open(ctx context.Context, org, profile string, rows, cols int) (*Session, error) {
p, err := m.Profile(profile) p, err := m.Profile(profile)
if err != nil { if err != nil {
return nil, fmt.Errorf("%w: %s", ErrProfileUnknown, profile) return nil, fmt.Errorf("%w: %s", ErrProfileUnknown, profile)
@@ -74,7 +84,8 @@ func (m *Manager) Open(ctx context.Context, org, profile string) (*Session, erro
_ = m.Launcher.Release(context.WithoutCancel(ctx), run) _ = m.Launcher.Release(context.WithoutCancel(ctx), run)
return nil, fmt.Errorf("%w: %s", ErrNoShell, p.Kit) return nil, fmt.Errorf("%w: %s", ErrNoShell, p.Kit)
} }
pty, err := container.ExecPTY(ctx, m.Client, run.Container.ID, run.Harness.User, run.Harness.Env, shell, 24, 80) pty, err := container.ExecPTY(ctx, m.Client, run.Container.ID, run.Harness.User, run.Harness.Env, shell,
uint(terminalSize(rows, terminalDefaultRows)), uint(terminalSize(cols, terminalDefaultCols)))
if err != nil { if err != nil {
_ = m.Launcher.Release(context.WithoutCancel(ctx), run) _ = m.Launcher.Release(context.WithoutCancel(ctx), run)
return nil, err return nil, err
@@ -118,6 +129,14 @@ func (s *Session) Close() error {
return err return err
} }
// terminalSize bounds a requested row or column count.
func terminalSize(v, def int) int {
if v < 1 || v > terminalMaxCells {
return def
}
return v
}
// pickShell returns the login shell the image provides, preferring bash over // pickShell returns the login shell the image provides, preferring bash over
// sh, or ErrNoShell when it provides neither. The image, not archie, decides // sh, or ErrNoShell when it provides neither. The image, not archie, decides
// what is installed, so the probe runs in the container. // what is installed, so the probe runs in the container.
+26 -4
View File
@@ -7,7 +7,9 @@ import (
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"net/url"
"sort" "sort"
"strconv"
"strings" "strings"
"time" "time"
@@ -47,10 +49,28 @@ type harnessProfileDoc struct {
Kit string `json:"kit"` Kit string `json:"kit"`
} }
// HarnessTerminal opens a setup session to a Kit profile's container PTY. // HarnessTerminal opens a setup session to a Kit profile's container PTY at
// Nil answers 503. // the requested terminal size, in character cells. Nil answers 503.
type HarnessTerminal interface { type HarnessTerminal interface {
Open(ctx context.Context, orgID, profile string) (io.ReadWriteCloser, error) Open(ctx context.Context, orgID, profile string, rows, cols int) (io.ReadWriteCloser, error)
}
// Terminal geometry: the dashboard's fallback when a size is absent or out of
// range, and the largest it will ask for.
const (
terminalDefaultRows = 24
terminalDefaultCols = 80
terminalMaxCells = 1000
)
// terminalSize reads a positive row or column count from the query, falling
// back to def when it is absent or out of range rather than failing the open.
func terminalSize(query url.Values, key string, def int) int {
n, err := strconv.Atoi(query.Get(key))
if err != nil || n < 1 || n > terminalMaxCells {
return def
}
return n
} }
// harnessBindingView is one credential binding as the page renders it: the // harnessBindingView is one credential binding as the page renders it: the
@@ -182,7 +202,9 @@ func (s *Server) handleHarnessTerminal(w http.ResponseWriter, r *http.Request) {
http.Error(w, "profile is required", http.StatusBadRequest) http.Error(w, "profile is required", http.StatusBadRequest)
return return
} }
session, err := s.HarnessTerminal.Open(r.Context(), string(org.OrgFromContext(r.Context())), profile) rows := terminalSize(r.URL.Query(), "rows", terminalDefaultRows)
cols := terminalSize(r.URL.Query(), "cols", terminalDefaultCols)
session, err := s.HarnessTerminal.Open(r.Context(), string(org.OrgFromContext(r.Context())), profile, rows, cols)
if err != nil { if err != nil {
s.logf("open setup terminal", "err", err, "profile", profile) s.logf("open setup terminal", "err", err, "profile", profile)
http.Error(w, "setup terminal failed", http.StatusBadGateway) http.Error(w, "setup terminal failed", http.StatusBadGateway)
+10
View File
@@ -23,6 +23,10 @@ message OpenRequest {
// stdin is terminal input bytes. // stdin is terminal input bytes.
bytes stdin = 2; bytes stdin = 2;
} }
// size is the terminal size the client wants, in character cells. The
// dashboard sends it with the target frame so the PTY is created at the
// right size; the daemon falls back to its own default when it is absent.
ConsoleSize size = 3;
} }
// OpenResponse is one server frame. // OpenResponse is one server frame.
@@ -60,3 +64,9 @@ message RunTarget {
int64 task_id = 1; int64 task_id = 1;
int64 attempt = 2; int64 attempt = 2;
} }
// ConsoleSize is a terminal size in character cells.
message ConsoleSize {
uint32 rows = 1;
uint32 cols = 2;
}
+1 -1
View File
@@ -13,4 +13,4 @@ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){t
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),oa&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=ka(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Wi(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-Aa),Aa),t/=Aa,t/Math.abs(t)+Math.round(t*(ja-1)))}shouldForceSelection(e){return na?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Ma)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(na&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._active Line truncated `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),oa&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=ka(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Wi(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-Aa),Aa),t/=Aa,t/Math.abs(t)+Math.round(t*(ja-1)))}shouldForceSelection(e){return na?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Ma)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(na&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._active Line truncated
`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(F(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(k(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<Es+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` `))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(F(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(k(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<Es+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Es+1&&(this._liveRegion.textContent+=T.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r Line truncated `&&(this._liveRegionLineCount++,this._liveRegionLineCount===Es+1&&(this._liveRegion.textContent+=T.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r Line truncated
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return be.get()},set promptLabel(e){be.set(e)},get tooMuchOutput(){return T.get()},set tooMuchOutput(e){T.set(e)}}}_verifyIntegers(...e){for(zs of e)if(zs===1/0||isNaN(zs)||zs%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(zs of e)if(zs&&(zs===1/0||isNaN(zs)||zs%1!=0||zs<0))throw Error(`This API only accepts positive integers`)}},Vs=2,Hs=1,Us=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(Vs,Math.floor(u/e.css.cell.width)),rows:Math.max(Hs,Math.floor(l/e.css.cell.height))}}};function Ws(e,t=Date.now()){if(!e.captured)return`unconfigured`;if(!e.expires_at)return`ready`;let n=Date.parse(e.expires_at);return Number.isNaN(n)?`ready`:n<=t?`expired`:n-t<=18e5?`expiring`:`ready`}function Gs(e,t){let n=t.protocol===`https:`?`wss:`:`ws:`,r=new URLSearchParams({profile:e}).toString();return`${n}//${t.host}/api/harness/terminal?${r}`}var Ks={class:`flex h-full min-h-0 flex-col gap-2`},qs={key:0,class:`text-sm text-muted-foreground`,role:`status`},Js=e({__name:`SetupTerminal`,props:{profile:{}},setup(e){let n=e,r=_(null),i=_(`connecting`),c=null,u=null,f=null,h=null;function g(){try{f?.fit()}catch{}}return l(()=>{let e=r.value;if(!e)return;c=new Bs({convertEol:!0,cursorBlink:!0,fontFamily:`'IBM Plex Mono', ui-monospace, monospace`,fontSize:13,theme:{background:`#0b0f14`,foreground:`#e6edf3`,cursor:`#e6edf3`,selectionBackground:`#264f78`}}),f=new Us,c.loadAddon(f),c.open(e),g(),c.focus();let t=new WebSocket(Gs(n.profile,window.location));u=t,t.binaryType=`arraybuffer`,t.onopen=()=>{i.value=`open`},t.onmessage=e=>{c&&(typeof e.data==`string`?c.write(e.data):c.write(new Uint8Array(e.data)))},t.onerror=()=>{i.value=`failed`},t.onclose=()=>{i.value=`closed`},c.onData(e=>{t.readyState===WebSocket.OPEN&&t.send(e)}),h=new ResizeObserver(g),h.observe(e)}),a(()=>{h?.disconnect(),h=null,u?.close(),u=null,c?.dispose(),c=null,f=null}),(e,n)=>(s(),m(`div`,Ks,[i.value===`open`?o(``,!0):(s(),m(`p`,qs,[i.value===`connecting`?(s(),m(d,{key:0},[t(`Connecting…`)],64)):i.value===`closed`?(s(),m(d,{key:1},[t(`The terminal session ended.`)],64)):(s(),m(d,{key:2},[t(`Could not open the setup terminal.`)],64))])),p(`div`,{ref_key:`host`,ref:r,class:`min-h-0 flex-1 overflow-hidden rounded-md border border-border bg-[#0b0f14] p-2`},null,512)]))}}),Ys={key:0,class:`mb-4 text-sm text-danger`,role:`alert`},Xs={key:1,class:`space-y-2`},Zs={class:`flex flex-col gap-1 text-sm`},Qs=[`disabled`],$s={key:0,value:``},ec=[`value`],tc=e({__name:`HarnessPage`,setup(e){let a=_(null),x=_(!0),ve=_(null),S=_(!1),C=_(``),w=_(!1),ye={ready:{label:`Ready`,variant:`ok`},expiring:{label:`Expiring soon`,variant:`warn`},expired:{label:`Expired`,variant:`danger`},unconfigured:{label:`Not set up`,variant:`idle`}};l(be);async function be(){x.value=!0,ve.value=null,S.value=!1;try{let e=await te.harnessBindings();a.value={terminal:e.terminal,bindings:e.bindings??[],profiles:e.profiles??[]},C.value=a.value.profiles[0]??``}catch(e){let t=e instanceof ie?e.status:void 0;t===501||t===503?S.value=!0:ve.value=e instanceof Error?e.message:String(e),a.value=null}finally{x.value=!1}}function xe(){a.value?.terminal&&C.value&&(w.value=!0)}function T(e){if(!e)return`—`;let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function Se(e){return e.scopes?.length?e.scopes.join(`, `):`—`}return(e,l)=>(s(),m(`div`,null,[r(f,{title:`Harness`}),ve.value?(s(),m(`p`,Ys,u(ve.value),1)):o(``,!0),x.value?(s(),m(`div`,Xs,[r(c(ge),{class:`h-24 w-full`}),r(c(ge),{class:`h-40 w-full`})])):S.value?(s(),g(c(v),{key:2},{default:n(()=>[r(c(de),null,{default:n(()=>[r(c(pe),null,{default:n(()=>[...l[1]||=[t(`Harness bindings are not configured`,-1)]]),_:1} Line truncated `,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return be.get()},set promptLabel(e){be.set(e)},get tooMuchOutput(){return T.get()},set tooMuchOutput(e){T.set(e)}}}_verifyIntegers(...e){for(zs of e)if(zs===1/0||isNaN(zs)||zs%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(zs of e)if(zs&&(zs===1/0||isNaN(zs)||zs%1!=0||zs<0))throw Error(`This API only accepts positive integers`)}},Vs=2,Hs=1,Us=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(Vs,Math.floor(u/e.css.cell.width)),rows:Math.max(Hs,Math.floor(l/e.css.cell.height))}}};function Ws(e,t=Date.now()){if(!e.captured)return`unconfigured`;if(!e.expires_at)return`ready`;let n=Date.parse(e.expires_at);return Number.isNaN(n)?`ready`:n<=t?`expired`:n-t<=18e5?`expiring`:`ready`}function Gs(e,t,n=80,r=24){let i=t.protocol===`https:`?`wss:`:`ws:`,a=new URLSearchParams({profile:e,cols:String(n),rows:String(r)}).toString();return`${i}//${t.host}/api/harness/terminal?${a}`}var Ks={class:`flex h-full min-h-0 flex-col gap-2`},qs={key:0,class:`text-sm text-muted-foreground`,role:`status`},Js=e({__name:`SetupTerminal`,props:{profile:{}},setup(e){let n=e,r=_(null),i=_(`connecting`),c=null,u=null,f=null,h=null;function g(){try{f?.fit()}catch{}}return l(()=>{let e=r.value;if(!e)return;c=new Bs({convertEol:!0,cursorBlink:!0,fontFamily:`'IBM Plex Mono', ui-monospace, monospace`,fontSize:13,theme:{background:`#0b0f14`,foreground:`#e6edf3`,cursor:`#e6edf3`,selectionBackground:`#264f78`}}),f=new Us,c.loadAddon(f),c.open(e),g(),c.focus();let t=new WebSocket(Gs(n.profile,window.location,c?.cols??80,c?.rows??24));u=t,t.binaryType=`arraybuffer`,t.onopen=()=>{i.value=`open`},t.onmessage=e=>{c&&(typeof e.data==`string`?c.write(e.data):c.write(new Uint8Array(e.data)))},t.onerror=()=>{i.value=`failed`},t.onclose=()=>{i.value=`closed`},c.onData(e=>{t.readyState===WebSocket.OPEN&&t.send(e)}),h=new ResizeObserver(g),h.observe(e)}),a(()=>{h?.disconnect(),h=null,u?.close(),u=null,c?.dispose(),c=null,f=null}),(e,n)=>(s(),m(`div`,Ks,[i.value===`open`?o(``,!0):(s(),m(`p`,qs,[i.value===`connecting`?(s(),m(d,{key:0},[t(`Connecting…`)],64)):i.value===`closed`?(s(),m(d,{key:1},[t(`The terminal session ended.`)],64)):(s(),m(d,{key:2},[t(`Could not open the setup terminal.`)],64))])),p(`div`,{ref_key:`host`,ref:r,class:`min-h-0 flex-1 overflow-hidden rounded-md border border-border bg-[#0b0f14] p-2`},null,512)]))}}),Ys={key:0,class:`mb-4 text-sm text-danger`,role:`alert`},Xs={key:1,class:`space-y-2`},Zs={class:`flex flex-col gap-1 text-sm`},Qs=[`disabled`],$s={key:0,value:``},ec=[`value`],tc=e({__name:`HarnessPage`,setup(e){let a=_(null),x=_(!0),ve=_(null),S=_(!1),C=_(``),w=_(!1),ye={ready:{label:`Ready`,variant:`ok`},expiring:{label:`Expiring soon`,variant:`warn`},expired:{label:`Expired`,variant:`danger`},unconfigured:{label:`Not set up`,variant:`idle`}};l(be);async function be(){x.value=!0,ve.value=null,S.value=!1;try{let e=await te.harnessBindings();a.value={terminal:e.terminal,bindings:e.bindings??[],profiles:e.profiles??[]},C.value=a.value.profiles[0]??``}catch(e){let t=e instanceof ie?e.status:void 0;t===501||t===503?S.value=!0:ve.value=e instanceof Error?e.message:String(e),a.value=null}finally{x.value=!1}}function xe(){a.value?.terminal&&C.value&&(w.value=!0)}function T(e){if(!e)return`—`;let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function Se(e){return e.scopes?.length?e.scopes.join(`, `):`—`}return(e,l)=>(s(),m(`div`,null,[r(f,{title:`Harness`}),ve.value?(s(),m(`p`,Ys,u(ve.value),1)):o(``,!0),x.value?(s(),m(`div`,Xs,[r(c(ge),{class:`h-24 w-full`}),r(c(ge),{class:`h-40 w-full`})])):S.value?(s(),g(c(v),{key:2},{default:n(()=>[r(c(de),null,{default:n(()=>[r(c(pe),null,{default:n(()= Line truncated
+6 -5
View File
@@ -6,10 +6,9 @@
* set headers on a WebSocket, so the shared-token gate reads the same * set headers on a WebSocket, so the shared-token gate reads the same
* HttpOnly cookie the SSE stream uses. * HttpOnly cookie the SSE stream uses.
* *
* The transport is raw bytes in both directions. Sizing the remote PTY is a * The transport is raw bytes in both directions. The component measures its
* contract detail the daemon side will own with the session, so this * own box before connecting and sends that size so the remote PTY is created
* component fits the local surface but does not claim to resize the * at the right geometry; live resize is not wired yet.
* container.
*/ */
import { onBeforeUnmount, onMounted, ref } from "vue"; import { onBeforeUnmount, onMounted, ref } from "vue";
import { Terminal } from "@xterm/xterm"; import { Terminal } from "@xterm/xterm";
@@ -59,7 +58,9 @@ onMounted(() => {
fitLocal(); fitLocal();
term.focus(); term.focus();
const ws = new WebSocket(setupTerminalURL(props.profile, window.location)); const ws = new WebSocket(
setupTerminalURL(props.profile, window.location, term?.cols ?? 80, term?.rows ?? 24),
);
socket = ws; socket = ws;
ws.binaryType = "arraybuffer"; ws.binaryType = "arraybuffer";
ws.onopen = () => { ws.onopen = () => {
+11 -4
View File
@@ -53,15 +53,22 @@ export function bindingStatus(
} }
/** /**
* setupTerminalURL builds the WebSocket URL for one Kit profile. The location * setupTerminalURL builds the WebSocket URL for one Kit profile, carrying the
* is a parameter rather than window so the module stays runnable outside a * terminal size the browser measured so the remote PTY is created with it.
* browser. * The location is a parameter rather than window so the module stays runnable
* outside a browser.
*/ */
export function setupTerminalURL( export function setupTerminalURL(
profile: string, profile: string,
location: Pick<Location, "protocol" | "host">, location: Pick<Location, "protocol" | "host">,
cols = 80,
rows = 24,
): string { ): string {
const scheme = location.protocol === "https:" ? "wss:" : "ws:"; const scheme = location.protocol === "https:" ? "wss:" : "ws:";
const query = new URLSearchParams({ profile }).toString(); const query = new URLSearchParams({
profile,
cols: String(cols),
rows: String(rows),
}).toString();
return `${scheme}//${location.host}/api/harness/terminal?${query}`; return `${scheme}//${location.host}/api/harness/terminal?${query}`;
} }
+26 -6
View File
@@ -29,11 +29,31 @@ test("credential status distinguishes uncaptured, ready, expiring and expired bi
} }
}); });
test("setup terminals preserve secure transport and encode the profile", () => { test("setup terminals preserve secure transport, encode the profile and carry the size", () => {
for (const [profile, location, expected] of [ const cases: Array<[string, Pick<Location, "protocol" | "host">, number, number, string]> = [
["claude-kit", { protocol: "http:", host: "127.0.0.1:8484" }, "ws://127.0.0.1:8484/api/harness/terminal?profile=claude-kit"], [
["claude kit", { protocol: "https:", host: "archie.example" }, "wss://archie.example/api/harness/terminal?profile=claude+kit"], "claude-kit",
] as const) { { protocol: "http:", host: "127.0.0.1:8484" },
assert.equal(setupTerminalURL(profile, location), expected, profile); 80,
24,
"ws://127.0.0.1:8484/api/harness/terminal?profile=claude-kit&cols=80&rows=24",
],
[
"claude kit",
{ protocol: "https:", host: "archie.example" },
80,
24,
"wss://archie.example/api/harness/terminal?profile=claude+kit&cols=80&rows=24",
],
[
"claude-kit",
{ protocol: "https:", host: "archie.example" },
120,
30,
"wss://archie.example/api/harness/terminal?profile=claude-kit&cols=120&rows=30",
],
];
for (const [profile, location, cols, rows, expected] of cases) {
assert.equal(setupTerminalURL(profile, location, cols, rows), expected, profile);
} }
}); });