Merge branch 'feature/windows': Windows support
This commit is contained in:
commit
159c5e8fbc
24 files changed
+377
-70
No files matched your search
@@ -1,5 +1,5 @@
|
||||
# Pushing a tag like v0.1.0 builds a binary per platform, runs each on its own OS, and
|
||||
# publishes them as a GitHub Release for install.sh and `t3tui upgrade`. Run it by hand
|
||||
# publishes them as a GitHub Release for install.sh, install.ps1 and `t3tui upgrade`. Run it by hand
|
||||
# to build and check the binaries without releasing them.
|
||||
name: Release
|
||||
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
- run: bun run typecheck
|
||||
- run: bun run lint
|
||||
- run: bun test
|
||||
- run: bun run compile linux-x64 linux-arm64 darwin-x64 darwin-arm64
|
||||
- run: bun run compile linux-x64 linux-arm64 darwin-x64 darwin-arm64 windows-x64
|
||||
- name: Compress and checksum
|
||||
working-directory: release
|
||||
run: |
|
||||
@@ -72,9 +72,22 @@ jobs:
|
||||
grep -q "Waiting for threads" out.txt || { cat out.txt; echo "the dashboard didn't draw"; exit 1; }
|
||||
kill $!
|
||||
|
||||
# Windows has no `script` to give the dashboard a terminal, so this stops at the binary starting.
|
||||
smoke-windows:
|
||||
needs: build
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release
|
||||
- run: gunzip -c t3tui-windows-x64.exe.gz > t3tui.exe && ./t3tui.exe version
|
||||
|
||||
release:
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
needs: smoke
|
||||
needs: [smoke, smoke-windows]
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -94,6 +107,7 @@ jobs:
|
||||
Built against T3 Code \`${t3code:-$commit}\`.
|
||||
|
||||
Install: \`curl -fsSL https://raw.githubusercontent.com/${{ github.repository }}/main/install.sh | sh\`
|
||||
On Windows: \`irm https://raw.githubusercontent.com/${{ github.repository }}/main/install.ps1 | iex\`
|
||||
Already installed: \`t3tui upgrade\`
|
||||
EOF
|
||||
gh release create "$GITHUB_REF_NAME" release/* --title "$GITHUB_REF_NAME" --notes-file notes.md --generate-notes
|
||||
@@ -18,11 +18,17 @@ You need a T3 Code server running on the same machine (or a token for a remote o
|
||||
curl -fsSL https://raw.githubusercontent.com/callumalpass/t3tui/main/install.sh | sh
|
||||
```
|
||||
|
||||
That puts a single `t3tui` binary in `~/.local/bin` (set `T3TUI_INSTALL_DIR` to change it). It needs nothing else installed, not even Bun. `t3tui upgrade` replaces it with the latest release, and `t3tui version` says which you have. Each release notes the T3 Code version it was built against.
|
||||
On Windows, in PowerShell:
|
||||
|
||||
```powershell
|
||||
irm https://raw.githubusercontent.com/callumalpass/t3tui/main/install.ps1 | iex
|
||||
```
|
||||
|
||||
That puts a single `t3tui` binary in `~/.local/bin`, or `%LOCALAPPDATA%\Programs\t3tui` on Windows, which it adds to your PATH (set `T3TUI_INSTALL_DIR` to change it). It needs nothing else installed, not even Bun. `t3tui upgrade` replaces it with the latest release, and `t3tui version` says which you have. Each release notes the T3 Code version it was built against.
|
||||
|
||||
### Build from source
|
||||
|
||||
On other systems (Windows, or Linux with musl), or to run unreleased changes, you need [Bun](https://bun.sh) 1.3.14 or later:
|
||||
On other systems (such as Linux with musl), or to run unreleased changes, you need [Bun](https://bun.sh) 1.3.14 or later:
|
||||
|
||||
```sh
|
||||
git clone --recurse-submodules https://github.com/callumalpass/t3tui.git && cd t3tui
|
||||
@@ -38,7 +44,7 @@ After pulling changes, run `bun run build` (or `bun install`) to rebuild.
|
||||
t3tui # dashboard: threads on the left, the selected thread on the right
|
||||
t3tui attach <thread> # one thread, full screen (id, short id from `t3tui list`, or title text)
|
||||
t3tui list [--json] # print threads and exit
|
||||
t3tui tmux [--watch] # mirror active threads into a tmux session, one window each
|
||||
t3tui tmux [--watch] # mirror active threads into a tmux session, one window each (not on Windows)
|
||||
```
|
||||
|
||||
The message box is always at the bottom. t3tui has two modes: **typing**, where keys go to the message box, and **navigation**, where single keys act. `esc` switches to navigation; `i`, `enter` or `tab` switch back.
|
||||
|
||||
+1
-1
@@ -37,6 +37,6 @@ Releases are standalone binaries built with `bun build --compile`, so users don'
|
||||
git tag v0.1.0 && git push origin v0.1.0
|
||||
```
|
||||
|
||||
The [Release workflow](../.github/workflows/release.yml) compiles linux-x64, linux-arm64, darwin-x64 and darwin-arm64 on one machine, opens each binary's dashboard on its own OS, and publishes them gzipped with a `SHA256SUMS` file, which `install.sh` and `t3tui upgrade` both check. Run the workflow by hand to build and check the binaries without releasing.
|
||||
The [Release workflow](../.github/workflows/release.yml) compiles linux-x64, linux-arm64, darwin-x64, darwin-arm64 and windows-x64 on one machine, opens each binary's dashboard on its own OS (on Windows it only runs `t3tui version`), and publishes them gzipped with a `SHA256SUMS` file, which `install.sh`, `install.ps1` and `t3tui upgrade` all check. Run the workflow by hand to build and check the binaries without releasing.
|
||||
|
||||
To build a binary locally, run `bun run compile` (this machine) or name targets, e.g. `bun run compile darwin-arm64`. Other platforms' targets need their OpenTUI packages: `bun install --os='*' --cpu='*'`. Binaries go in `release/`.
|
||||
+4
-4
@@ -76,7 +76,7 @@ Navigation:
|
||||
|
||||
`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; the `followUpBehavior` setting swaps the two. With an approval pending, a typed message declines it with your feedback.
|
||||
|
||||
`shift+enter` adds a newline (it needs a terminal with the kitty keyboard protocol); so does ending the line with `\` and pressing `enter`. The box grows up to 8 lines. `ctrl+g` opens the message in `$VISUAL` or `$EDITOR` (falling back to `vi`) in the message box's place; save and quit to bring it back.
|
||||
`shift+enter` adds a newline (it needs a terminal with the kitty keyboard protocol); so does ending the line with `\` and pressing `enter`. The box grows up to 8 lines. `ctrl+g` opens the message in `$VISUAL` or `$EDITOR` (falling back to `vi`, or `notepad` on Windows) in the message box's place; save and quit to bring it back.
|
||||
|
||||
`ctrl+v` attaches the clipboard's image, or pastes its text when there is no image. Pasting or dropping the path of an image file (quoted, as a `file://` URL, or with `\ ` before spaces) attaches the file rather than typing the path. See [Attachments](#attachments).
|
||||
|
||||
@@ -120,7 +120,7 @@ The layout follows T3 Code's web app, and much of it uses the web app's own code
|
||||
|
||||
- **Select and copy:** drag across any text, in the conversation or a terminal or editor, to select it; it's copied when you let go (through the terminal with OSC 52, and the desktop clipboard locally) and `Copied` shows at the bottom. A program in a terminal or editor that takes the mouse itself, like an editor with mouse support, gets the drag instead. A single click still does what it did. A key press clears the highlight. Your terminal's own selection still works with shift held.
|
||||
- **Buttons:** approvals, questions (click an option), secret requests, confirmations, queued messages (click one to send it now, edit or remove it), attached files (✕ removes one) and the PR view have buttons, each with its key beside it. Every hint along the bottom that names one key is clickable, and so is `commands` at the top.
|
||||
- **Conversation:** a click on a prompt selects that turn, as `[`/`]` do; a click on a folded turn or work group opens just that one; a click on a command shows its output; "Load earlier turns" loads them. In a reply, links are underlined in the accent colour and a click opens them in the browser (`xdg-open`, or `open` on macOS); a click on a path to a file in the workspace, like `src/ui/App.tsx:12`, opens it in a tab of the right-hand column. In a diff, a click on a file selects it and a second click shows the whole file. In the PR view, the URL opens in the browser. In the Files tab, a click selects a row, a click on a folder opens or closes it, and a click on the selected file opens it.
|
||||
- **Conversation:** a click on a prompt selects that turn, as `[`/`]` do; a click on a folded turn or work group opens just that one; a click on a command shows its output; "Load earlier turns" loads them. In a reply, links are underlined in the accent colour and a click opens them in the browser (`xdg-open`, `open` on macOS, the default browser on Windows); a click on a path to a file in the workspace, like `src/ui/App.tsx:12`, opens it in a tab of the right-hand column. In a diff, a click on a file selects it and a second click shows the whole file. In the PR view, the URL opens in the browser. In the Files tab, a click selects a row, a click on a folder opens or closes it, and a click on the selected file opens it.
|
||||
- **Right-click menus:** on a thread (its actions), a prompt (copy, view its changes, revert), a reply (copy), a command (copy the command or its output) and the PR view (its actions).
|
||||
- **Panes:** clicking the conversation takes the keys out of the message box, details or a pane; clicking the message box types; clicking a pane gives it the keys. A click on a tab switches to it, the active tab's ✕ closes it, and a middle-click closes any tab. The wheel scrolls the conversation, the thread list (without moving the selection) and the palette. Drag the thread list's right edge, the right-hand column's left edge or the terminal drawer's top edge to resize it; right-click the edge to reset it.
|
||||
|
||||
@@ -143,7 +143,7 @@ Submenus open as their own list, and typing finds their items from the top (`thr
|
||||
|
||||
## Attachments
|
||||
|
||||
`a` in navigation (or `Attach file…` in the palette) prompts for a path: `~` expands, and a relative path is taken from the thread's worktree or project folder. `ctrl+v` in the message box, or `Paste image from clipboard` in the palette, takes the clipboard's image instead (PNG, JPEG, WebP or GIF), as does a paste that comes through empty, which is how many terminals pass on a copied image. The clipboard is read through OpenTUI, then `wl-paste` or `xclip` (or `pngpaste` or `osascript` on macOS) when that finds nothing it can read. Over SSH the clipboard is on the other machine, so use `a` there. Pasting an image file's path attaches the file. Files upload at once, and their names show above the message box until the next message sends them; `Remove attachment: …` in the palette takes one back. A message can be attachments alone.
|
||||
`a` in navigation (or `Attach file…` in the palette) prompts for a path: `~` expands, and a relative path is taken from the thread's worktree or project folder. `ctrl+v` in the message box, or `Paste image from clipboard` in the palette, takes the clipboard's image instead (PNG, JPEG, WebP or GIF), as does a paste that comes through empty, which is how many terminals pass on a copied image. The clipboard is read through OpenTUI, then `wl-paste` or `xclip` (`pngpaste` or `osascript` on macOS, PowerShell on Windows) when that finds nothing it can read. Over SSH the clipboard is on the other machine, so use `a` there. Pasting an image file's path attaches the file. Files upload at once, and their names show above the message box until the next message sends them; `Remove attachment: …` in the palette takes one back. A message can be attachments alone.
|
||||
|
||||
Sent images show in their message, up to 12 rows tall, through kitty or sixel graphics where the terminal has them and as coloured blocks elsewhere; the file's name is under each.
|
||||
|
||||
@@ -167,7 +167,7 @@ While the drawer has focus, every key goes to its program, `esc` included, apart
|
||||
|
||||
`Pane: move terminal to the side` in the palette puts terminals in the right-hand column instead, each a tab in the column's one strip: `Details · <editors> · Terminal 1 · Terminal 2 · + new`. `Pane: move terminal below` puts them back. The choice is kept for the next run. A narrow column cuts long tab names to fit; drag its edge to widen it.
|
||||
|
||||
`$VISUAL` or `$EDITOR` (falling back to `vi`) runs on this machine in the same way: `ctrl+g` writes the message in it, in the message box's place, and `o` on a file under Changes in the details panel (or its `▸ Edit`), or a click on a workspace path in a reply, opens that file in a tab of the right-hand column, when the workspace is on this machine. Each file gets its own tab, named by its path in the workspace (cut from the middle when long, `src/…/TerminalPane.tsx`). With Neovim (`nvim`), the first file starts it with `--listen` on a socket in a temp folder, and later files open in that same Neovim (`--server … --remote-expr`), whose tab takes the keys and the file's name. When an editor exits, its tab closes and the column goes back to Details, or hides again if the editor is what showed it. With the column hidden (`d`) while an editor runs, `Editor: <file> · d` shows at the right of the strip under the message box, or of the header, with `●` when Neovim has unsaved changes.
|
||||
`$VISUAL` or `$EDITOR` (falling back to `vi`, or `notepad` on Windows) runs on this machine in the same way: `ctrl+g` writes the message in it, in the message box's place, and `o` on a file under Changes in the details panel (or its `▸ Edit`), or a click on a workspace path in a reply, opens that file in a tab of the right-hand column, when the workspace is on this machine. Each file gets its own tab, named by its path in the workspace (cut from the middle when long, `src/…/TerminalPane.tsx`). With Neovim (`nvim`), the first file starts it with `--listen` on a socket in a temp folder (a named pipe on Windows), and later files open in that same Neovim (`--server … --remote-expr`), whose tab takes the keys and the file's name. When an editor exits, its tab closes and the column goes back to Details, or hides again if the editor is what showed it. With the column hidden (`d`) while an editor runs, `Editor: <file> · d` shows at the right of the strip under the message box, or of the header, with `●` when Neovim has unsaved changes.
|
||||
|
||||
`T` opens the terminal picker even with only one terminal. Choose `New terminal`, `Attach full screen` (the whole screen goes to the terminal until `ctrl+j` or `ctrl+]`), `Close terminal…` or `Clear terminal…`; typing `close` or `clear` finds each terminal's action directly. Closing ends the shell and deletes its history, so it asks first; clearing clears its scrollback. The palette has the same under `Terminal:` (`Terminal: open`, `Terminal: new`, `Terminal: attach full screen`, `Terminal: pick…`), with close and clear for the active terminal (`Terminal: close Terminal 1`).
|
||||
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
# Installs the t3tui binary from GitHub Releases:
|
||||
# irm https://raw.githubusercontent.com/callumalpass/t3tui/main/install.ps1 | iex
|
||||
# T3TUI_INSTALL_DIR picks where it goes (default %LOCALAPPDATA%\Programs\t3tui); T3TUI_VERSION picks a release (e.g. 0.1.0).
|
||||
# Run through iex, so it throws rather than exits: exit would close the terminal.
|
||||
& {
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
# Windows PowerShell 5.1 may not offer TLS 1.2 by default.
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
|
||||
|
||||
$repo = 'callumalpass/t3tui'
|
||||
$dir = if ($env:T3TUI_INSTALL_DIR) { $env:T3TUI_INSTALL_DIR } else { Join-Path $env:LOCALAPPDATA 'Programs\t3tui' }
|
||||
# Windows on Arm runs the x64 build under emulation.
|
||||
$file = 't3tui-windows-x64.exe.gz'
|
||||
$base = if ($env:T3TUI_VERSION) { "https://github.com/$repo/releases/download/v$($env:T3TUI_VERSION -replace '^v', '')" } else { "https://github.com/$repo/releases/latest/download" }
|
||||
|
||||
$tmp = Join-Path ([IO.Path]::GetTempPath()) ([IO.Path]::GetRandomFileName())
|
||||
New-Item -ItemType Directory -Path $tmp | Out-Null
|
||||
try {
|
||||
Write-Host "Downloading $file..."
|
||||
Invoke-WebRequest -UseBasicParsing -Uri "$base/$file" -OutFile "$tmp\$file"
|
||||
Invoke-WebRequest -UseBasicParsing -Uri "$base/SHA256SUMS" -OutFile "$tmp\SHA256SUMS"
|
||||
|
||||
$listed = Get-Content "$tmp\SHA256SUMS" | Where-Object { ($_ -split '\s+\*?')[1] -eq $file } | Select-Object -First 1
|
||||
$expected = if ($listed) { ($listed -split '\s+')[0] } else { $null }
|
||||
$actual = (Get-FileHash -Algorithm SHA256 "$tmp\$file").Hash
|
||||
if (-not $expected -or $expected -ne $actual) { throw "$file doesn't match its checksum; nothing was installed" }
|
||||
|
||||
$source = [IO.File]::OpenRead("$tmp\$file")
|
||||
$target = [IO.File]::Create("$tmp\t3tui.exe")
|
||||
try {
|
||||
$gunzip = New-Object IO.Compression.GZipStream($source, [IO.Compression.CompressionMode]::Decompress)
|
||||
$gunzip.CopyTo($target)
|
||||
} finally {
|
||||
$target.Dispose()
|
||||
$source.Dispose()
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $dir | Out-Null
|
||||
# A running t3tui can't be replaced, but it can be moved aside; it removes that copy on its next start.
|
||||
$exe = Join-Path $dir 't3tui.exe'
|
||||
if (Test-Path $exe) { Move-Item -Force $exe "$exe.old-$PID" }
|
||||
Move-Item "$tmp\t3tui.exe" $exe
|
||||
Write-Host "Installed $(& $exe version) to $exe"
|
||||
|
||||
$path = [Environment]::GetEnvironmentVariable('Path', 'User')
|
||||
if (($path -split ';') -notcontains $dir) {
|
||||
[Environment]::SetEnvironmentVariable('Path', ($(if ($path) { "$path;$dir" } else { $dir })), 'User')
|
||||
$env:Path = "$env:Path;$dir"
|
||||
Write-Host "Added $dir to your PATH. Terminals already open need a restart to see it."
|
||||
}
|
||||
} finally {
|
||||
Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
+7
-5
@@ -8,9 +8,11 @@ import { existsSync } from "node:fs";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
const TARGETS = ["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64"];
|
||||
const TARGETS = ["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64", "windows-x64"];
|
||||
// Every native package OpenTUI might import. Each binary keeps only its own platform's.
|
||||
const NATIVE = [...TARGETS, "linux-x64-musl", "linux-arm64-musl", "win32-x64", "win32-arm64"].map((t) => `@opentui/core-${t}`);
|
||||
const NATIVE = ["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64", "linux-x64-musl", "linux-arm64-musl", "win32-x64", "win32-arm64"].map((t) => `@opentui/core-${t}`);
|
||||
/** Bun names Windows "windows"; npm and OpenTUI's packages call it "win32". */
|
||||
const nativeOf = (target: string) => `@opentui/core-${target.replace(/^windows-/, "win32-")}`;
|
||||
|
||||
const root = join(import.meta.dir, "..");
|
||||
const outdir = join(root, "release");
|
||||
@@ -18,15 +20,15 @@ const targets = process.argv.slice(2);
|
||||
if (targets.length === 0) targets.push(`${process.platform}-${process.arch}`);
|
||||
for (const target of targets) {
|
||||
if (!TARGETS.includes(target)) throw new Error(`unknown target ${target}; expected one of ${TARGETS.join(", ")}`);
|
||||
if (!existsSync(join(root, "node_modules/@opentui", `core-${target}`))) {
|
||||
throw new Error(`@opentui/core-${target} isn't installed; run bun install --os='*' --cpu='*'`);
|
||||
if (!existsSync(join(root, "node_modules", nativeOf(target)))) {
|
||||
throw new Error(`${nativeOf(target)} isn't installed; run bun install --os='*' --cpu='*'`);
|
||||
}
|
||||
}
|
||||
|
||||
await mkdir(outdir, { recursive: true });
|
||||
for (const target of targets) {
|
||||
const outfile = join(outdir, `t3tui-${target}`);
|
||||
const external = NATIVE.filter((name) => name !== `@opentui/core-${target}`).flatMap((name) => ["--external", name]);
|
||||
const external = NATIVE.filter((name) => name !== nativeOf(target)).flatMap((name) => ["--external", name]);
|
||||
// OpenTUI starts its syntax highlighter from parser.worker.js, so it's compiled in as a second entrypoint.
|
||||
await $`bun build --compile --minify --target=bun-${target} ${external} ${join(root, "src/bin.ts")} ${join(root, "node_modules/@opentui/core/parser.worker.js")} --outfile ${outfile}`.cwd(root);
|
||||
}
|
||||
+3
-1
@@ -3,7 +3,7 @@ import type { OrchestrationV2ShellSnapshot, ThreadId } from "@t3tools/contracts"
|
||||
|
||||
import { migrateConfigDir } from "./client/auth.ts";
|
||||
import { T3Session } from "./client/session.ts";
|
||||
import { isCompiled, upgrade, VERSION } from "./upgrade.ts";
|
||||
import { isCompiled, removeOldBinaries, upgrade, VERSION } from "./upgrade.ts";
|
||||
import { findThread, lastActivity, relativeTime, rowTime, shortId, statusLabel, threadRows } from "./model/threads.ts";
|
||||
|
||||
const USAGE = `t3tui: a terminal client for T3 Code
|
||||
@@ -24,6 +24,7 @@ env:
|
||||
|
||||
async function main(argv: string[]) {
|
||||
migrateConfigDir();
|
||||
if (process.platform === "win32" && isCompiled()) removeOldBinaries();
|
||||
const [command, ...rest] = argv;
|
||||
switch (command) {
|
||||
case undefined:
|
||||
@@ -89,6 +90,7 @@ async function list(json: boolean) {
|
||||
}
|
||||
|
||||
async function tmuxCommand(args: string[]) {
|
||||
if (process.platform === "win32") return fail("t3tui tmux needs tmux, which doesn't run on Windows. Run it inside WSL instead.");
|
||||
const { syncTmux } = await import("./mux/tmux.ts");
|
||||
const sessionFlag = args.indexOf("--session");
|
||||
const name = sessionFlag >= 0 ? args[sessionFlag + 1] : "t3tui";
|
||||
|
||||
@@ -11,6 +11,8 @@ import { clampFileAttachmentUploadBytes, fileAttachmentTooLargeMessage } from "@
|
||||
import { homedir } from "node:os";
|
||||
import { basename, isAbsolute, resolve } from "node:path";
|
||||
|
||||
import { isWindowsAbsolute } from "./paths.ts";
|
||||
|
||||
const IMAGE_MIME_BY_EXTENSION: Readonly<Record<string, string>> = {
|
||||
gif: "image/gif",
|
||||
jpeg: "image/jpeg",
|
||||
@@ -28,7 +30,7 @@ export function imageMimeTypeForName(name: string): string | null {
|
||||
/** Expands `~` and resolves a relative path against `cwd`, as the attach prompt promises. */
|
||||
export function expandAttachmentPath(input: string, cwd: string | null): string {
|
||||
const path = input.trim();
|
||||
const expanded = path === "~" ? homedir() : path.startsWith("~/") ? resolve(homedir(), path.slice(2)) : path;
|
||||
const expanded = path === "~" ? homedir() : path.startsWith("~/") || path.startsWith("~\\") ? resolve(homedir(), path.slice(2)) : path;
|
||||
return isAbsolute(expanded) ? expanded : resolve(cwd ?? process.cwd(), expanded);
|
||||
}
|
||||
|
||||
@@ -46,8 +48,13 @@ export interface ClipboardImageTool {
|
||||
readonly decode?: (stdout: Uint8Array) => Uint8Array | null;
|
||||
}
|
||||
|
||||
/** Prints the clipboard's image as base64 PNG, and nothing when it holds none. Reading the clipboard needs -STA. */
|
||||
const WINDOWS_CLIPBOARD_IMAGE =
|
||||
"Add-Type -AssemblyName System.Windows.Forms,System.Drawing; $image = [Windows.Forms.Clipboard]::GetImage(); if ($image) { $stream = New-Object IO.MemoryStream; $image.Save($stream, [Drawing.Imaging.ImageFormat]::Png); [Convert]::ToBase64String($stream.ToArray()) }";
|
||||
|
||||
/** The clipboard readers, in order: the platform's usual image grabber first. */
|
||||
export function clipboardImageCommands(platform: string): readonly ClipboardImageTool[] {
|
||||
if (platform === "win32") return [{ read: () => ["powershell.exe", "-NoProfile", "-NonInteractive", "-STA", "-Command", WINDOWS_CLIPBOARD_IMAGE], mimeType: "image/png", decode: (stdout) => Buffer.from(new TextDecoder().decode(stdout).trim(), "base64") }];
|
||||
return platform === "darwin"
|
||||
? [
|
||||
{ read: () => ["pngpaste", "-"], mimeType: "image/png" },
|
||||
@@ -90,13 +97,16 @@ export function pastedImagePath(text: string, cwd: string | null): string | null
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
if (url.hostname && url.hostname !== "localhost") return null;
|
||||
path = decodeURIComponent(url.pathname);
|
||||
// `file:///C:/a.png` is a Windows path, whole, after its first slash.
|
||||
path = decodeURIComponent(url.pathname).replace(/^\/(?=[A-Za-z]:\/)/, "");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
path = raw.replace(/\\(.)/g, "$1");
|
||||
// A Windows path's backslashes are its folders, not escapes.
|
||||
path = isWindowsAbsolute(raw) ? raw : raw.replace(/\\(.)/g, "$1");
|
||||
}
|
||||
if (isWindowsAbsolute(path)) return imageMimeTypeForName(path) ? path : null;
|
||||
if (!path.startsWith("/") && !path.startsWith("~") && !path.startsWith(".")) return null;
|
||||
return imageMimeTypeForName(path) ? expandAttachmentPath(path, cwd) : null;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import type {
|
||||
VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { formatWorkingDurationLabel, type ThreadStructureTurnItem } from "@t3tools/client-runtime/state/models";
|
||||
import { homedir } from "node:os";
|
||||
import { tildify } from "./paths.ts";
|
||||
|
||||
import type { VcsState } from "../client/session.ts";
|
||||
import { formatClock, type T3tuiConfig } from "../config.ts";
|
||||
@@ -379,10 +379,6 @@ function prState(state: string, draft: boolean): { state: string; tone: StatusTo
|
||||
return { state, tone: "muted" };
|
||||
}
|
||||
|
||||
function tildify(path: string): string {
|
||||
const home = homedir();
|
||||
return path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
|
||||
}
|
||||
|
||||
const LIVE_SUBAGENT: ReadonlySet<string> = new Set(["pending", "running", "waiting"]);
|
||||
type SubagentStatus = "running" | "failed" | "done";
|
||||
|
||||
+4
-5
@@ -1,5 +1,5 @@
|
||||
import type { ProjectEntry } from "@t3tools/contracts";
|
||||
import { homedir } from "node:os";
|
||||
import { tildify } from "./paths.ts";
|
||||
|
||||
import type { ChangedFile } from "./details.ts";
|
||||
|
||||
@@ -72,11 +72,10 @@ const IMAGE_EXTENSIONS: ReadonlySet<string> = new Set(["png", "jpg", "jpeg", "gi
|
||||
|
||||
/** `~/…/project`: the root with the home folder shortened, cut from the middle to `width`. */
|
||||
export function rootLabel(root: string, width: number): string {
|
||||
const home = homedir();
|
||||
const path = root === home || root.startsWith(`${home}/`) ? `~${root.slice(home.length)}` : root;
|
||||
const path = tildify(root);
|
||||
if (path.length <= width) return path;
|
||||
const name = nameOf(path);
|
||||
const head = path.startsWith("~/") ? "~/…/" : "…/";
|
||||
const head = path.startsWith("~/") || path.startsWith("~\\") ? "~/…/" : "…/";
|
||||
return head.length + name.length <= width ? `${head}${name}` : `…${name.slice(Math.max(0, name.length - width + 1))}`;
|
||||
}
|
||||
|
||||
@@ -85,4 +84,4 @@ export function sizeLabel(bytes: number): string {
|
||||
return bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
const nameOf = (path: string) => path.slice(path.lastIndexOf("/") + 1);
|
||||
const nameOf = (path: string) => path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
|
||||
+21
-8
@@ -1,22 +1,35 @@
|
||||
/** Characters a file path on screen is made of, with an optional `:line` or `:line:col` after it. */
|
||||
const PATH_CHARS = /[\w.~/@+-]/;
|
||||
|
||||
/** On Windows, backslashes too. */
|
||||
const WINDOWS_PATH_CHARS = /[\w.~/\\@+-]/;
|
||||
|
||||
/**
|
||||
* The file path the text has at `index`, as an agent writes them: `src/ui/App.tsx`,
|
||||
* `./bin.ts:12`, `~/notes.md`. Null for words, URLs and anything else without a folder
|
||||
* or an extension.
|
||||
* `./bin.ts:12`, `~/notes.md`, and on Windows `src\ui\App.tsx` and `C:\notes.md`. Null for
|
||||
* words, URLs and anything else without a folder or an extension.
|
||||
*/
|
||||
export function pathAt(text: string, index: number): string | null {
|
||||
if (!PATH_CHARS.test(text[index] ?? "")) return null;
|
||||
export function pathAt(text: string, index: number, platform: string = process.platform): string | null {
|
||||
const windows = platform === "win32";
|
||||
const chars = windows ? WINDOWS_PATH_CHARS : PATH_CHARS;
|
||||
if (!chars.test(text[index] ?? "")) return null;
|
||||
let start = index;
|
||||
let end = index + 1;
|
||||
while (start > 0 && PATH_CHARS.test(text[start - 1]!)) start--;
|
||||
while (end < text.length && (PATH_CHARS.test(text[end]!) || (text[end] === ":" && /\d/.test(text[end + 1] ?? "")))) end++;
|
||||
while (start > 0 && chars.test(text[start - 1]!)) start--;
|
||||
while (end < text.length && (chars.test(text[end]!) || (text[end] === ":" && /\d/.test(text[end + 1] ?? "")))) end++;
|
||||
// The drive's colon, which is no line number: `C:\notes.md`.
|
||||
if (windows && text[start - 1] === ":" && /(?:^|[^\w])[A-Za-z]$/.test(text.slice(Math.max(0, start - 3), start - 1)) && /[\\/]/.test(text[start] ?? "")) start -= 2;
|
||||
if (text[start - 1] === ":" || text.slice(end, end + 3) === "://") return null;
|
||||
const token = text.slice(start, end).replace(/[.,]+$/, "");
|
||||
const path = token.replace(/(:\d+){1,2}$/, "");
|
||||
if (!/[\w~]/.test(path[0] ?? "") && !path.startsWith("./") && !path.startsWith("../") && !path.startsWith("/")) return null;
|
||||
return path.includes("/") || /\.[A-Za-z]\w*$/.test(path) ? path : null;
|
||||
if (!/[\w~]/.test(path[0] ?? "") && !path.startsWith("./") && !path.startsWith("../") && !path.startsWith("/") && !(windows && /^\.{0,2}\\/.test(path))) return null;
|
||||
return path.includes("/") || (windows && path.includes("\\")) || /\.[A-Za-z]\w*$/.test(path) ? path : null;
|
||||
}
|
||||
|
||||
/** The command that opens a web link in the desktop's browser. Windows' goes round cmd, which would split a URL at its `&`. */
|
||||
export function browserCommand(url: string, platform: string = process.platform): string[] {
|
||||
if (platform === "win32") return ["rundll32.exe", "url.dll,FileProtocolHandler", url];
|
||||
return [platform === "darwin" ? "open" : "xdg-open", url];
|
||||
}
|
||||
|
||||
/** A link's target is a web page unless it is a bare path. */
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { homedir } from "node:os";
|
||||
|
||||
/** A path with the home folder as `~`, whichever way the path's slashes lean. */
|
||||
export function tildify(path: string, home: string = homedir()): string {
|
||||
return path === home || path.startsWith(`${home}/`) || path.startsWith(`${home}\\`) ? `~${path.slice(home.length)}` : path;
|
||||
}
|
||||
|
||||
/** Whether this is a Windows path no folder can be relative to: `C:\x`, `C:/x` or `\\server\x`. */
|
||||
export const isWindowsAbsolute = (path: string) => /^(?:[A-Za-z]:[\\/]|\\\\)/.test(path);
|
||||
@@ -149,7 +149,7 @@ export function rowTime(thread: OrchestrationV2ThreadShell): number {
|
||||
|
||||
export function projectLabel(project: OrchestrationProjectShell | undefined): string {
|
||||
if (!project) return "";
|
||||
return project.title || project.workspaceRoot.split("/").filter(Boolean).pop() || project.workspaceRoot;
|
||||
return project.title || project.workspaceRoot.split(/[\\/]/).filter(Boolean).pop() || project.workspaceRoot;
|
||||
}
|
||||
|
||||
/** Matches a thread by id, id prefix, or a case-insensitive title substring. */
|
||||
|
||||
+2
-2
@@ -4,7 +4,6 @@ import { resolveComposerDispatchMode } from "@t3tools/client-runtime/state/compo
|
||||
import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
|
||||
import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts";
|
||||
import { existsSync, statSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { isAbsolute, join, relative } from "node:path";
|
||||
import { parseFileUrlHref, resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
@@ -73,6 +72,7 @@ import { useThreadLibrary } from "./useThreadLibrary.ts";
|
||||
import { usePaletteSearch } from "./usePaletteSearch.ts";
|
||||
import { useThreadFind } from "./useThreadFind.ts";
|
||||
import { ThreadFindBar } from "./ThreadFindBar.tsx";
|
||||
import { tildify } from "../model/paths.ts";
|
||||
import { mergeThreadShells, messageMatchGroups } from "../model/search.ts";
|
||||
import { useAttachments } from "./useAttachments.ts";
|
||||
import { useAutomations } from "./useAutomations.ts";
|
||||
@@ -1397,7 +1397,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
serverStatus={serverConfig?.status ?? "loading"}
|
||||
usage={[...usageInfo.lines, ...usageSummaryLines(usage.summary), ...(usage.failed && !usage.summary ? [{ label: "Last 30 days", value: "could not read usage" }] : [])]}
|
||||
selected={settingsIndex}
|
||||
path={configPath().replace(homedir(), "~")}
|
||||
path={tildify(configPath())}
|
||||
onCycle={(index) => {
|
||||
setMode("settings");
|
||||
cycleSetting(index);
|
||||
|
||||
+12
-1
@@ -170,16 +170,27 @@ function attachServer(session: T3Session, target: TerminalTarget, term: Embedded
|
||||
* stops listening for SIGWINCH and so never sees the pane change size.
|
||||
*/
|
||||
function withoutInBandResize(data: Uint8Array): Uint8Array {
|
||||
// biome-ignore lint/suspicious/noControlCharactersInRegex: this matches an escape sequence
|
||||
return Buffer.from(Buffer.from(data).toString("latin1").replace(/\x1b\[\?2048;\d\$y/g, "\x1b[?2048;0$y"), "latin1");
|
||||
}
|
||||
|
||||
/** A program run here on its own pty, answering its terminal queries through the emulator. */
|
||||
function spawnLocal(program: Extract<PaneProgram, { kind: "local" }>, term: EmbeddedTerminalRenderable, cols: number, rows: number, close: (message?: string) => void): Link {
|
||||
let stopped = false;
|
||||
const child = Bun.spawn([...program.command], {
|
||||
let child: ReturnType<typeof Bun.spawn>;
|
||||
try {
|
||||
child = Bun.spawn([...program.command], {
|
||||
...(program.cwd ? { cwd: program.cwd } : {}),
|
||||
terminal: { cols, rows, data: (_pty, data) => term.write(data) },
|
||||
});
|
||||
} catch (error) {
|
||||
// A missing program throws here, inside a resize; let the pane say so rather than the render loop.
|
||||
queueMicrotask(() => {
|
||||
program.onExit(127);
|
||||
close(`Couldn't start ${program.command[0]}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
});
|
||||
return { send: () => {}, resize: () => {}, stop: () => {} };
|
||||
}
|
||||
void child.exited.then((code) => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
|
||||
+44
-10
@@ -2,27 +2,46 @@ import type { CliRenderer } from "@opentui/core";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, join } from "node:path";
|
||||
import { join } from "node:path";
|
||||
|
||||
const editorSetting = () => process.env.VISUAL || process.env.EDITOR || "vi";
|
||||
const WINDOWS = process.platform === "win32";
|
||||
const editorSetting = () => process.env.VISUAL || process.env.EDITOR || (WINDOWS ? "notepad" : "vi");
|
||||
const shell = () => process.env.SHELL || "sh";
|
||||
/** The editor's program, without its arguments. */
|
||||
const editorProgram = () => editorSetting().trim().split(/\s+/)[0] ?? "vi";
|
||||
const editorProgram = () => (WINDOWS ? windowsWords(editorSetting())[0] : editorSetting().trim().split(/\s+/)[0]) ?? "vi";
|
||||
|
||||
/**
|
||||
* $VISUAL or $EDITOR (falling back to vi) on `file`, through the shell so EDITOR="code --wait" works.
|
||||
* $VISUAL or $EDITOR (falling back to vi, or notepad on Windows) on `file`, through the shell so EDITOR="code --wait" works.
|
||||
* With `listen`, Neovim serves that socket, so more files can go to it (see nvimRemote).
|
||||
*/
|
||||
export function editorCommand(file: string, listen?: string): string[] {
|
||||
const editor = editorSetting();
|
||||
if (WINDOWS) return [...windowsCommand(editor), ...(listen ? ["--listen", listen] : []), file];
|
||||
return listen ? [shell(), "-c", `${editor} --listen "$2" "$1"`, "sh", file, listen] : [shell(), "-c", `${editor} "$1"`, "sh", file];
|
||||
}
|
||||
|
||||
/** Whether the editor is Neovim, which can take more files and be asked to quit through a socket. */
|
||||
export const editorIsNvim = () => basename(editorProgram()) === "nvim";
|
||||
/** Splits a command line on spaces outside double quotes: `"C:\Program Files\Neovim\bin\nvim.exe" -p`. */
|
||||
export function windowsWords(command: string): string[] {
|
||||
return [...command.matchAll(/"([^"]*)"|(\S+)/g)].map((match) => match[1] ?? match[2]!);
|
||||
}
|
||||
|
||||
/** A socket for a Neovim started here, in a temp folder of its own (`remove` cleans up). Kept short: sockets have a length limit. */
|
||||
/** A command to run with no shell. Windows has no sh, and a .cmd like VS Code's `code` only runs through cmd. */
|
||||
export function windowsCommand(command: string, which: (program: string) => string | null = Bun.which): string[] {
|
||||
const [program = "", ...args] = windowsWords(command);
|
||||
const found = which(program) ?? program;
|
||||
// `call` keeps the line from starting with a quote, which cmd would strip along with the last one.
|
||||
return [...(/\.(?:cmd|bat)$/i.test(found) ? ["cmd.exe", "/c", "call"] : []), found, ...args];
|
||||
}
|
||||
|
||||
/** Whether this program, by name or path, is Neovim. */
|
||||
export const isNvim = (program: string) => /^nvim(?:\.exe)?$/i.test(program.split(/[\\/]/).pop() ?? "");
|
||||
|
||||
/** Whether the editor is Neovim, which can take more files and be asked to quit through a socket. */
|
||||
export const editorIsNvim = () => isNvim(editorProgram());
|
||||
|
||||
/** A socket for a Neovim started here, in a temp folder of its own (`remove` cleans up); on Windows, a named pipe. Kept short: sockets have a length limit. */
|
||||
export function nvimSocket(): { readonly path: string; readonly remove: () => void } {
|
||||
if (WINDOWS) return { path: `\\\\.\\pipe\\t3tui-nvim-${crypto.randomUUID()}`, remove: () => {} };
|
||||
const dir = mkdtempSync(join(tmpdir(), "t3tui-nvim-"));
|
||||
return { path: join(dir, "nvim.sock"), remove: () => rmSync(dir, { recursive: true, force: true }) };
|
||||
}
|
||||
@@ -33,7 +52,9 @@ export function nvimSocket(): { readonly path: string; readonly remove: () => vo
|
||||
* never fall back to editing in a Neovim of their own.
|
||||
*/
|
||||
export async function nvimRemote(socket: string, args: readonly string[]): Promise<string | null> {
|
||||
const child = Bun.spawn([shell(), "-c", `${editorProgram()} --server "$@"`, "sh", socket, ...args], { stdin: "ignore", stdout: "pipe", stderr: "ignore" });
|
||||
const command = WINDOWS ? [...windowsCommand(`"${editorProgram()}"`), "--server", socket, ...args] : [shell(), "-c", `${editorProgram()} --server "$@"`, "sh", socket, ...args];
|
||||
// windowsHide gives it a console of its own, as Neovim on Windows prints results to the console, not stdout.
|
||||
const child = Bun.spawn(command, { stdin: "ignore", stdout: "pipe", stderr: "ignore", windowsHide: true });
|
||||
const [code, output] = await Promise.all([child.exited, new Response(child.stdout).text()]);
|
||||
return code === 0 ? output : null;
|
||||
}
|
||||
@@ -44,10 +65,22 @@ export const nvimOpen = (socket: string, file: string) => nvimRemote(socket, ["-
|
||||
export const nvimQuit = (socket: string) => nvimRemote(socket, ["--remote-send", "<C-\\><C-N>:confirm qa<CR>"]);
|
||||
/** Whether the Neovim on `socket` has unsaved changes; null if it couldn't be reached. */
|
||||
export const nvimModified = async (socket: string) => {
|
||||
const count = await nvimRemote(socket, ["--remote-expr", "len(getbufinfo({'bufmodified': 1}))"]);
|
||||
const count = await nvimEval(socket, "len(getbufinfo({'bufmodified': 1}))");
|
||||
return count === null ? null : Number.parseInt(count, 10) > 0;
|
||||
};
|
||||
|
||||
/** What `expr` comes to in the Neovim on `socket`. Windows can't read its output (see nvimRemote), so there it's written to a file. */
|
||||
async function nvimEval(socket: string, expr: string): Promise<string | null> {
|
||||
if (!WINDOWS) return nvimRemote(socket, ["--remote-expr", expr]);
|
||||
const file = scratchFile("");
|
||||
try {
|
||||
const sent = await nvimRemote(socket, ["--remote-expr", `writefile([string(${expr})], ${vimString(file.path)})`]);
|
||||
return sent === null ? null : file.read();
|
||||
} finally {
|
||||
file.remove();
|
||||
}
|
||||
}
|
||||
|
||||
const vimString = (text: string) => `'${text.replaceAll("'", "''")}'`;
|
||||
|
||||
/** A scratch copy of `text` to edit: `read` returns what was saved, `remove` cleans up. */
|
||||
@@ -55,7 +88,8 @@ export function scratchFile(text: string): { readonly path: string; readonly rea
|
||||
const dir = mkdtempSync(join(tmpdir(), "t3tui-"));
|
||||
const path = join(dir, "prompt.md");
|
||||
writeFileSync(path, text);
|
||||
return { path, read: () => readFileSync(path, "utf8").replace(/\n$/, ""), remove: () => rmSync(dir, { recursive: true, force: true }) };
|
||||
// Windows editors may save CRLF.
|
||||
return { path, read: () => readFileSync(path, "utf8").replaceAll("\r\n", "\n").replace(/\n$/, ""), remove: () => rmSync(dir, { recursive: true, force: true }) };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+5
-3
@@ -1,13 +1,15 @@
|
||||
import type { CliRenderer } from "@opentui/core";
|
||||
|
||||
import { browserCommand } from "../model/links.ts";
|
||||
|
||||
/** Opens a web link in the desktop's browser; `fail` hears why it couldn't, as over SSH. */
|
||||
export function openInBrowser(url: string, fail: (reason: string) => void): void {
|
||||
try {
|
||||
const opener = process.platform === "darwin" ? "open" : "xdg-open";
|
||||
const command = browserCommand(url);
|
||||
// The environment as it is now: Bun otherwise looks the opener up on the PATH it started with.
|
||||
const child = Bun.spawn([opener, url], { env: process.env, stdin: "ignore", stdout: "ignore", stderr: "ignore" });
|
||||
const child = Bun.spawn(command, { env: process.env, stdin: "ignore", stdout: "ignore", stderr: "ignore" });
|
||||
void child.exited.then((code) => {
|
||||
if (code !== 0) fail(`${opener} exited with ${code}`);
|
||||
if (code !== 0) fail(`${command[0]} exited with ${code}`);
|
||||
});
|
||||
} catch (error) {
|
||||
fail(error instanceof Error ? error.message : String(error));
|
||||
|
||||
+2
-2
@@ -1,6 +1,5 @@
|
||||
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
|
||||
import type { ChatAttachment, ModelSelection, OrchestrationMessageContext, OrchestrationProjectShell, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ServerConfig, ThreadId } from "@t3tools/contracts";
|
||||
import { homedir } from "node:os";
|
||||
import { useState } from "react";
|
||||
|
||||
import type { T3Session } from "../client/session.ts";
|
||||
@@ -8,6 +7,7 @@ import { RUNTIME_MODE_LABELS } from "../model/details.ts";
|
||||
import type { Binding } from "../model/keymap.ts";
|
||||
import { draftDefaults, modelSummary, type DraftThread } from "../model/models.ts";
|
||||
import type { Picker } from "../model/palette.ts";
|
||||
import { tildify } from "../model/paths.ts";
|
||||
import type { DraftLine } from "./DraftView.tsx";
|
||||
|
||||
type WorkspaceStrategy = { type: "root" } | { type: "existing_worktree"; worktreePath: string } | { type: "worktree"; baseRef: string; startFromOrigin?: boolean };
|
||||
@@ -64,7 +64,7 @@ export function useDraft(deps: {
|
||||
items: projects.map((candidate) => ({
|
||||
id: `project:${candidate.id}`,
|
||||
title: candidate.title,
|
||||
hint: candidate.id === draft.projectId ? "current" : candidate.workspaceRoot.replace(homedir(), "~"),
|
||||
hint: candidate.id === draft.projectId ? "current" : tildify(candidate.workspaceRoot),
|
||||
run: () => setDraft(draftDefaults({ config, project: candidate, currentModel: draft.modelSelection, projectHasThreads: hasThreads(candidate.id) })),
|
||||
})),
|
||||
},
|
||||
|
||||
+44
-11
@@ -1,20 +1,26 @@
|
||||
// `t3tui upgrade`: replaces a released binary with the latest release's.
|
||||
import { chmod, rename, rm } from "node:fs/promises";
|
||||
import { realpathSync } from "node:fs";
|
||||
import { readdirSync, realpathSync, rmSync } from "node:fs";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
|
||||
export const VERSION = version;
|
||||
const REPO = "callumalpass/t3tui";
|
||||
const LATEST_URL = `https://api.github.com/repos/${REPO}/releases/latest`;
|
||||
const DOWNLOAD_URL = `https://github.com/${REPO}/releases/download`;
|
||||
|
||||
/** Bun's embedded filesystem: `/$bunfs/…`, or `B:\~BUN\…` on Windows. */
|
||||
export const isEmbeddedPath = (path: string) => path.startsWith("/$bunfs/") || /^[A-Za-z]:[\\/]~BUN[\\/]/.test(path);
|
||||
|
||||
/** A compiled binary runs its code from Bun's embedded filesystem. */
|
||||
export function isCompiled(): boolean {
|
||||
return import.meta.path.startsWith("/$bunfs/");
|
||||
return isEmbeddedPath(import.meta.path);
|
||||
}
|
||||
|
||||
/** The release asset for this machine, e.g. t3tui-linux-x64. */
|
||||
/** The release asset for this machine, e.g. t3tui-linux-x64 or t3tui-windows-x64.exe. */
|
||||
export function assetName(platform: string = process.platform, arch: string = process.arch): string {
|
||||
return `t3tui-${platform}-${arch}`;
|
||||
return platform === "win32" ? `t3tui-windows-${arch}.exe` : `t3tui-${platform}-${arch}`;
|
||||
}
|
||||
|
||||
/** Finds an asset's hash in a sha256sum listing. */
|
||||
@@ -31,7 +37,7 @@ export async function upgrade(): Promise<void> {
|
||||
console.log("t3tui is running from source. Update it with: git pull --recurse-submodules && bun install");
|
||||
return;
|
||||
}
|
||||
const latest = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, { headers: { accept: "application/vnd.github+json" } });
|
||||
const latest = await fetch(LATEST_URL, { headers: { accept: "application/vnd.github+json" } });
|
||||
if (latest.status === 404) throw new Error("No t3tui release has been published yet.");
|
||||
if (!latest.ok) throw new Error(`Couldn't check for a new release (GitHub answered ${latest.status}).`);
|
||||
const tag = ((await latest.json()) as { tag_name: string }).tag_name;
|
||||
@@ -40,27 +46,54 @@ export async function upgrade(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
const file = `${assetName()}.gz`;
|
||||
const base = `https://github.com/${REPO}/releases/download/${tag}`;
|
||||
const base = `${DOWNLOAD_URL}/${tag}`;
|
||||
const [archive, sums] = await Promise.all([download(`${base}/${file}`), download(`${base}/SHA256SUMS`)]);
|
||||
const expected = checksumFor(new TextDecoder().decode(sums), file);
|
||||
if (!expected) throw new Error(`Release ${tag} has no ${file}.`);
|
||||
const actual = new Bun.CryptoHasher("sha256").update(archive).digest("hex");
|
||||
if (actual !== expected) throw new Error(`The downloaded ${file} doesn't match its checksum; nothing was changed.`);
|
||||
|
||||
// Renaming over the running binary is safe: the running process keeps the old file open.
|
||||
const target = realpathSync(process.execPath);
|
||||
await replaceBinary(realpathSync(process.execPath), Bun.gunzipSync(archive));
|
||||
console.log(`t3tui ${VERSION} → ${tag.replace(/^v/, "")}`);
|
||||
}
|
||||
|
||||
/** Puts `binary` where `target` is, which may be the running program. */
|
||||
export async function replaceBinary(target: string, binary: Uint8Array, platform: string = process.platform): Promise<void> {
|
||||
const temporary = `${target}.upgrade-${process.pid}`;
|
||||
try {
|
||||
await Bun.write(temporary, Bun.gunzipSync(archive));
|
||||
await Bun.write(temporary, binary);
|
||||
if (platform === "win32") {
|
||||
// Windows won't let a running .exe be replaced, or deleted, but it can be moved aside.
|
||||
const aside = `${target}${OLD_SUFFIX}${process.pid}`;
|
||||
await rename(target, aside);
|
||||
await rename(temporary, target).catch(async (error) => {
|
||||
await rename(aside, target);
|
||||
throw error;
|
||||
});
|
||||
} else {
|
||||
// Renaming over the running binary is safe: the running process keeps the old file open.
|
||||
await chmod(temporary, 0o755);
|
||||
await rename(temporary, target);
|
||||
}
|
||||
} catch (error) {
|
||||
await rm(temporary, { force: true });
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === "EACCES" || code === "EPERM") throw new Error(`Can't write ${target}. Rerun with permission to replace it (e.g. sudo t3tui upgrade).`);
|
||||
if (code === "EACCES" || code === "EPERM") throw new Error(`Can't write ${target}. ${platform === "win32" ? "Rerun from an administrator terminal." : "Rerun with permission to replace it (e.g. sudo t3tui upgrade)."}`);
|
||||
throw error;
|
||||
}
|
||||
console.log(`t3tui ${VERSION} → ${tag.replace(/^v/, "")}`);
|
||||
}
|
||||
|
||||
const OLD_SUFFIX = ".old-";
|
||||
|
||||
/** Deletes what an upgrade moved aside on Windows; one another t3tui still runs stays for next time. */
|
||||
export function removeOldBinaries(target: string = process.execPath): void {
|
||||
const folder = dirname(target);
|
||||
for (const name of readdirSync(folder)) {
|
||||
if (!name.startsWith(`${basename(target)}${OLD_SUFFIX}`)) continue;
|
||||
try {
|
||||
rmSync(join(folder, name));
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
async function download(url: string): Promise<Uint8Array<ArrayBuffer>> {
|
||||
|
||||
@@ -117,3 +117,15 @@ describe("pasted paths", () => {
|
||||
expect(pastedImagePath("", null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
test("a dropped Windows file keeps its backslashes", () => {
|
||||
expect(pastedImagePath('"C:\\Users\\me\\shot.png"', null)).toBe("C:\\Users\\me\\shot.png");
|
||||
expect(pastedImagePath("file:///C:/Users/me/my%20shot.png", null)).toBe("C:/Users/me/my shot.png");
|
||||
expect(pastedImagePath("C:\\Users\\me\\notes.txt", null)).toBeNull();
|
||||
});
|
||||
|
||||
test("on Windows, the clipboard's image comes through PowerShell as base64", () => {
|
||||
const [tool] = clipboardImageCommands("win32");
|
||||
expect(tool?.read("image/png")[0]).toBe("powershell.exe");
|
||||
expect(tool?.decode?.(new TextEncoder().encode("iVBORw==\r\n"))).toEqual(Buffer.from([0x89, 0x50, 0x4e, 0x47]));
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { writeFileSync } from "node:fs";
|
||||
|
||||
import { isNvim, scratchFile, windowsCommand, windowsWords } from "../src/ui/editor.ts";
|
||||
|
||||
test("splits a Windows command line on spaces outside quotes", () => {
|
||||
expect(windowsWords('"C:\\Program Files\\Git\\usr\\bin\\vim.exe" -p')).toEqual(["C:\\Program Files\\Git\\usr\\bin\\vim.exe", "-p"]);
|
||||
expect(windowsWords("code --wait")).toEqual(["code", "--wait"]);
|
||||
});
|
||||
|
||||
test("runs a .cmd through cmd, and anything else as it is", () => {
|
||||
const which = (program: string) => ({ code: "C:\\VS Code\\bin\\code.cmd", nvim: "C:\\nvim\\nvim.exe" })[program] ?? null;
|
||||
expect(windowsCommand("code --wait", which)).toEqual(["cmd.exe", "/c", "call", "C:\\VS Code\\bin\\code.cmd", "--wait"]);
|
||||
expect(windowsCommand("nvim", which)).toEqual(["C:\\nvim\\nvim.exe"]);
|
||||
expect(windowsCommand("missing", which)).toEqual(["missing"]);
|
||||
});
|
||||
|
||||
test("knows Neovim by name or path", () => {
|
||||
expect(isNvim("nvim")).toBe(true);
|
||||
expect(isNvim("/usr/bin/nvim")).toBe(true);
|
||||
expect(isNvim("C:\\Program Files\\Neovim\\bin\\nvim.exe")).toBe(true);
|
||||
expect(isNvim("vim")).toBe(false);
|
||||
});
|
||||
|
||||
test("reads back a scratch file saved with CRLF", () => {
|
||||
const file = scratchFile("");
|
||||
writeFileSync(file.path, "one\r\ntwo\r\n");
|
||||
expect(file.read()).toBe("one\ntwo");
|
||||
file.remove();
|
||||
});
|
||||
+26
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
|
||||
import { isWebUrl, pathAt } from "../src/model/links.ts";
|
||||
import { browserCommand, isWebUrl, pathAt } from "../src/model/links.ts";
|
||||
|
||||
const at = (text: string, word: string) => pathAt(text, text.indexOf(word));
|
||||
|
||||
@@ -34,3 +34,28 @@ describe("paths in text", () => {
|
||||
expect(isWebUrl("src/ui/App.tsx")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("on Windows", () => {
|
||||
test("finds paths with backslashes and drives", () => {
|
||||
const text = "see src\\ui\\App.tsx:12 and C:\\Users\\me\\notes.md, or ..\\a.ts";
|
||||
expect(pathAt(text, text.indexOf("App"), "win32")).toBe("src\\ui\\App.tsx");
|
||||
expect(pathAt(text, text.indexOf("Users"), "win32")).toBe("C:\\Users\\me\\notes.md");
|
||||
expect(pathAt(text, text.indexOf("a.ts"), "win32")).toBe("..\\a.ts");
|
||||
});
|
||||
|
||||
test("leaves URLs and line numbers alone", () => {
|
||||
expect(pathAt("https://example.com/a", 12, "win32")).toBeNull();
|
||||
expect(pathAt("at a:b/c.ts", 8, "win32")).toBeNull();
|
||||
});
|
||||
|
||||
test("backslashes are not path characters elsewhere", () => {
|
||||
expect(pathAt("src\\ui\\App.tsx", 8, "linux")).toBe("App.tsx");
|
||||
});
|
||||
});
|
||||
|
||||
test("opens the browser the platform's way, past cmd's reach on Windows", () => {
|
||||
const url = "https://example.com/?a=1&b=2";
|
||||
expect(browserCommand(url, "linux")).toEqual(["xdg-open", url]);
|
||||
expect(browserCommand(url, "darwin")).toEqual(["open", url]);
|
||||
expect(browserCommand(url, "win32")).toEqual(["rundll32.exe", "url.dll,FileProtocolHandler", url]);
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { expect, test } from "bun:test";
|
||||
|
||||
import { isWindowsAbsolute, tildify } from "../src/model/paths.ts";
|
||||
|
||||
test("shortens the home folder, on either kind of slash", () => {
|
||||
expect(tildify("/home/me/projects", "/home/me")).toBe("~/projects");
|
||||
expect(tildify("/home/me", "/home/me")).toBe("~");
|
||||
expect(tildify("/home/mean/projects", "/home/me")).toBe("/home/mean/projects");
|
||||
expect(tildify("C:\\Users\\me\\projects", "C:\\Users\\me")).toBe("~\\projects");
|
||||
expect(tildify("C:\\Users\\mean", "C:\\Users\\me")).toBe("C:\\Users\\mean");
|
||||
});
|
||||
|
||||
test("knows a Windows absolute path", () => {
|
||||
expect(isWindowsAbsolute("C:\\a.png")).toBe(true);
|
||||
expect(isWindowsAbsolute("c:/a.png")).toBe(true);
|
||||
expect(isWindowsAbsolute("\\\\server\\share\\a.png")).toBe(true);
|
||||
expect(isWindowsAbsolute("/a.png")).toBe(false);
|
||||
expect(isWindowsAbsolute("a.png")).toBe(false);
|
||||
});
|
||||
+36
-1
@@ -1,9 +1,44 @@
|
||||
import { expect, test } from "bun:test";
|
||||
|
||||
import { assetName, checksumFor, isCompiled } from "../src/upgrade.ts";
|
||||
import { existsSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { assetName, checksumFor, isCompiled, isEmbeddedPath, removeOldBinaries, replaceBinary } from "../src/upgrade.ts";
|
||||
|
||||
test("names the release asset for a platform", () => {
|
||||
expect(assetName("darwin", "arm64")).toBe("t3tui-darwin-arm64");
|
||||
expect(assetName("win32", "x64")).toBe("t3tui-windows-x64.exe");
|
||||
});
|
||||
|
||||
test("knows Bun's embedded filesystem on every platform", () => {
|
||||
expect(isEmbeddedPath("/$bunfs/root/t3tui-linux-x64")).toBe(true);
|
||||
expect(isEmbeddedPath("B:\\~BUN\\root\\t3tui-windows-x64.exe")).toBe(true);
|
||||
expect(isEmbeddedPath("B:/~BUN/root/t3tui-windows-x64.exe")).toBe(true);
|
||||
expect(isEmbeddedPath("/home/me/t3tui/src/upgrade.ts")).toBe(false);
|
||||
expect(isEmbeddedPath("C:\\t3tui\\src\\upgrade.ts")).toBe(false);
|
||||
});
|
||||
|
||||
test("on Windows, moves the old binary aside and removes it on the next start", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "t3tui-upgrade-"));
|
||||
const target = join(dir, "t3tui.exe");
|
||||
writeFileSync(target, "old");
|
||||
writeFileSync(join(dir, "notes.txt"), "mine");
|
||||
await replaceBinary(target, new TextEncoder().encode("new"), "win32");
|
||||
expect(readFileSync(target, "utf8")).toBe("new");
|
||||
expect(readdirSync(dir).filter((name) => name.includes(".old-"))).toHaveLength(1);
|
||||
removeOldBinaries(target);
|
||||
expect(readdirSync(dir).sort()).toEqual(["notes.txt", "t3tui.exe"]);
|
||||
});
|
||||
|
||||
test("elsewhere, renames straight over the binary", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "t3tui-upgrade-"));
|
||||
const target = join(dir, "t3tui");
|
||||
writeFileSync(target, "old");
|
||||
await replaceBinary(target, new TextEncoder().encode("new"), "linux");
|
||||
expect(readFileSync(target, "utf8")).toBe("new");
|
||||
expect(readdirSync(dir)).toEqual(["t3tui"]);
|
||||
expect(existsSync(`${target}.upgrade-${process.pid}`)).toBe(false);
|
||||
});
|
||||
|
||||
test("reads a hash from a sha256sum listing", () => {
|
||||
|
||||
Reference in new issue
Block a user