Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 34 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,53 @@ jobs:
bun-version: 1.3.6

- name: Install locked dependencies
id: install
run: bun install --frozen-lockfile

- name: Install Linux sandbox test dependencies
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y bubblewrap socat

- name: Format
if: ${{ !cancelled() && steps.install.outcome == 'success' && runner.os == 'Linux' }}
run: bun run format:check

- name: Architecture boundaries
if: ${{ !cancelled() && steps.install.outcome == 'success' && runner.os == 'Linux' }}
run: bun run architecture:check

- name: Security audit
run: bun run security:audit
- name: Focused runtime and CLI regressions
if: ${{ !cancelled() && steps.install.outcome == 'success' && runner.os != 'Linux' }}
run: >-
bun test
./packages/runtime/src/test/unit/sandboxEnv.test.ts
./packages/runtime/src/test/unit/sandboxBoundaries.test.ts
./packages/runtime/src/test/unit/shellCommandArgs.test.ts
./packages/runtime/src/test/unit/socatPaths.test.ts
./apps/cli/src/utils/externalEditor.test.ts
./packages/core/src/test/unit/git-hooks.test.ts
./packages/core/src/test/unit/cli-config-models-help.test.ts
./packages/core/src/test/unit/cli-context-help.test.ts
./packages/core/src/test/unit/cli-mcp-help.test.ts

- name: Typecheck
if: ${{ !cancelled() && steps.install.outcome == 'success' && runner.os == 'Linux' }}
run: bun run typecheck

- name: Test
- name: Isolated full test suite
if: ${{ !cancelled() && steps.install.outcome == 'success' && runner.os == 'Linux' }}
env:
KODE_REQUIRE_SANDBOX_TESTS: '1'
run: bun test

- name: Build
if: ${{ !cancelled() && steps.install.outcome == 'success' }}
run: bun run build

- name: Dependency security regressions
if: ${{ !cancelled() && steps.install.outcome == 'success' && runner.os == 'Linux' }}
env:
CI_AUDIT_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before || github.sha }}
run: |
git fetch --no-tags --depth=1 origin "$CI_AUDIT_BASE_SHA"
bun scripts/audit-regressions.mjs
2 changes: 2 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
#!/usr/bin/env sh

set -eu

bun run format:check
bun run typecheck
28 changes: 8 additions & 20 deletions apps/cli/src/commands/agent/agents/ui/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,17 @@ import type { OptionSubtree } from '#ui-ink/components/CustomSelect/select'
import { getModelManager } from '#core/utils/model'
import type { AgentSourceFilter } from './types'
import { DEFAULT_AGENT_MODEL } from './types'
import { getOpenTargetCmdForPlatform } from '#runtime/shell/shellCmd'

export function openInEditor(filePath: string): Promise<void> {
return new Promise((resolve, reject) => {
const platform = process.platform
let command: string
let args: string[]

switch (platform) {
case 'darwin':
command = 'open'
args = [filePath]
break
case 'win32':
command = 'cmd'
args = ['/c', 'start', '', filePath]
break
default:
command = 'xdg-open'
args = [filePath]
break
}

const child = spawn(command, args, { detached: true, stdio: 'ignore' })
const spec = getOpenTargetCmdForPlatform(process.platform, filePath)
const child = spawn(spec.cmd[0], spec.cmd.slice(1), {
detached: true,
stdio: 'ignore',
env: spec.env,
windowsVerbatimArguments: spec.windowsVerbatimArguments,
})
child.unref()
child.on('error', err => reject(err))
child.on('exit', code =>
Expand Down
31 changes: 14 additions & 17 deletions apps/cli/src/entrypoints/cli/cliParser/rootAction/webOnlyMode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,23 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
import { randomUUID } from 'node:crypto'
import { exec } from 'node:child_process'
import { spawn } from 'node:child_process'
import { LEGACY_ENV } from '#core/compat/legacyEnv'
import { getOpenTargetCmdForPlatform } from '#runtime/shell/shellCmd'

function openBrowser(url: string): void {
const platform = process.platform
let cmd: string

if (platform === 'darwin') {
cmd = `open "${url}"`
} else if (platform === 'win32') {
cmd = `start "" "${url}"`
} else {
cmd = `xdg-open "${url}"`
}

exec(cmd, err => {
if (err) {
// Silent fail - user can still click the link
}
})
try {
const spec = getOpenTargetCmdForPlatform(process.platform, url)
const child = spawn(spec.cmd[0], spec.cmd.slice(1), {
stdio: 'ignore',
detached: true,
env: spec.env,
windowsVerbatimArguments: spec.windowsVerbatimArguments,
})
// Browser opening is best effort; the URL is also printed in the terminal.
child.once('error', () => {})
child.unref()
} catch {}
}

function getKodeConfigDir(): string {
Expand Down
110 changes: 110 additions & 0 deletions apps/cli/src/utils/externalEditor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
import {
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { quote } from 'shell-quote'
import {
launchExternalEditor,
launchExternalEditorForFilePath,
} from './externalEditor'

describe('external editor command boundary', () => {
let root: string
let savedEnv: Record<string, string | undefined>
const keys = ['VISUAL', 'EDITOR', 'KODE_TEST_EDITOR_ARGS', 'TMPDIR'] as const

beforeEach(() => {
savedEnv = Object.fromEntries(keys.map(key => [key, process.env[key]]))
root = mkdtempSync(join(tmpdir(), 'kode-editor-'))
const editor = join(root, 'mock-editor.js')
const log = join(root, 'args.json')
writeFileSync(
editor,
"require('fs').writeFileSync(process.env.KODE_TEST_EDITOR_ARGS,JSON.stringify(process.argv.slice(2)))",
)
// VISUAL is a trusted command string and may include flags and a quoted program path.
process.env.VISUAL =
process.platform === 'win32'
? `"${process.execPath}" "${editor}" --wait`
: quote([process.execPath, editor, '--wait'])
delete process.env.EDITOR
process.env.KODE_TEST_EDITOR_ARGS = log
})

afterEach(() => {
for (const key of keys) {
if (savedEnv[key] === undefined) delete process.env[key]
else process.env[key] = savedEnv[key]
}
rmSync(root, { recursive: true, force: true })
})

describe('external editor filename boundary', () => {
const filenames =
process.platform === 'win32'
? ['file with spaces.txt', 'literal & %PATH% !bang! ^ (x).txt']
: [
'file with spaces.txt',
"O'Brien.txt",
'$(printf expanded).txt',
'literal`printf expanded`$HOME;file.txt',
'line\nbreak.txt',
]

test.each(filenames)(
'passes %j as exactly one literal argument',
async filename => {
const filePath = join(root, filename)
writeFileSync(filePath, 'example')
const result = await launchExternalEditorForFilePath(filePath)
expect(result.ok).toBe(true)
expect(
JSON.parse(readFileSync(process.env.KODE_TEST_EDITOR_ARGS!, 'utf8')),
).toEqual(['--wait', filePath])
},
)
})

test.skipIf(process.platform === 'win32')(
'temporary editor files also remain literal under a spaced TMPDIR',
async () => {
process.env.TMPDIR = join(root, 'temp with spaces')
mkdirSync(process.env.TMPDIR)
const result = await launchExternalEditor('draft\r\nline')
expect(result.text).toBe('draft\nline')
const args = JSON.parse(
readFileSync(process.env.KODE_TEST_EDITOR_ARGS!, 'utf8'),
)
expect(args[0]).toBe('--wait')
expect(args).toHaveLength(2)
expect(args[1]).toContain('temp with spaces')
expect(existsSync(args[1])).toBe(false)
},
)

test.skipIf(process.platform !== 'win32')(
'Windows cmd editor wrappers preserve percent, bang, caret and ampersand in paths',
async () => {
const wrapper = join(root, 'mock-editor.cmd')
writeFileSync(
wrapper,
`@echo off\r\n"${process.execPath}" "${join(root, 'mock-editor.js')}" %*\r\n`,
)
process.env.VISUAL = `"${wrapper}" --wait`
const filePath = join(root, 'literal %PATH% !bang! ^ & (x).txt')
writeFileSync(filePath, 'example')
const result = await launchExternalEditorForFilePath(filePath)
expect(result.ok).toBe(true)
expect(
JSON.parse(readFileSync(process.env.KODE_TEST_EDITOR_ARGS!, 'utf8')),
).toEqual(['--wait', filePath])
},
)
})
35 changes: 19 additions & 16 deletions apps/cli/src/utils/externalEditor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
import { writeToStdout } from '#cli-utils/stdio'
import { getInkInstanceForStdout } from '#ui-ink/utils/inkInstanceStore'
import { terminalCapabilityManager } from '#ui-ink/utils/terminalCapabilityManager'
import { getShellCmdWithArgsForPlatform } from '#runtime/shell/shellCmd'

type EditorCommand = {
command: string
Expand Down Expand Up @@ -144,6 +145,22 @@ function normalizeNewlines(text: string): string {
return text.replace(/\r\n/g, '\n')
}

function spawnEditor(editor: EditorCommand, filePath: string) {
const args = [...editor.args, filePath]
if (!editor.shell) return spawn(editor.command, args, { stdio: 'inherit' })

const spec = getShellCmdWithArgsForPlatform(
process.platform,
editor.command,
args,
)
return spawn(spec.cmd[0], spec.cmd.slice(1), {
stdio: 'inherit',
env: spec.env,
windowsVerbatimArguments: spec.windowsVerbatimArguments,
})
}

export type ExternalEditorResult =
| { text: string; editorLabel: string }
| { text: null; editorLabel?: string; error: Error }
Expand Down Expand Up @@ -176,14 +193,7 @@ export async function launchExternalEditor(
try {
await withSuspendedInk(async () => {
await new Promise<void>((resolve, reject) => {
const child = spawn(
editorCommand.command,
[...editorCommand.args, filePath],
{
stdio: 'inherit',
shell: editorCommand.shell ?? false,
},
)
const child = spawnEditor(editorCommand, filePath)

child.on('error', reject)
child.on('exit', (code, signal) => {
Expand Down Expand Up @@ -253,14 +263,7 @@ export async function launchExternalEditorForFilePath(
try {
await withSuspendedInk(async () => {
await new Promise<void>((resolve, reject) => {
const child = spawn(
editorCommand.command,
[...editorCommand.args, filePath],
{
stdio: 'inherit',
shell: editorCommand.shell ?? false,
},
)
const child = spawnEditor(editorCommand, filePath)

child.on('error', reject)
child.on('exit', (code, signal) => {
Expand Down
2 changes: 1 addition & 1 deletion bunfig.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
[test]
# Limit test discovery to the Bun-workspace test aggregator under `./test`.
# Limit test discovery to the Bun-workspace isolated workspace test runner under `./test`.
# This avoids accidentally running unrelated script-style files from the root.
root = "./test"
22 changes: 22 additions & 0 deletions docs/develop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,25 @@ bun run typecheck
bun test
bun run build
```

CI runs formatting, architecture checks, typechecking and the full test suite
once on Linux. macOS and Windows run the focused shell, sandbox, editor and CLI
regressions on native runners. All three platforms build the application.
Independent checks still run after another check fails, so the job reports all
failures instead of skipping validation after the first error.

`bun test` discovers every workspace test file and runs each in a fresh Bun
process with a temporary configuration directory. This isolates module mocks,
environment changes and caches on the pinned Bun 1.3.6 runtime. A missing test
completion summary is a failure even when a child exits with code zero. Linux
CI installs `bubblewrap` and `socat`; `KODE_REQUIRE_SANDBOX_TESTS=1` makes missing
socket capabilities or bridge prerequisites fail instead of silently skipping
the network integration tests. Restricted development environments may skip
those integrations explicitly.

The CI dependency gate compares the current lockfile with the trusted event
base commit and blocks newly introduced high/critical package-version/advisory
combinations. Both locks use the same advisory set. Existing vulnerabilities
remain visible in the job summary; this policy does **not** declare them fixed.
Registry failures and malformed responses fail the check. The full
`bun run security:audit` command above remains blocking for release validation.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@
"build:binary": "bun run scripts/build-binary.mjs",
"clean": "bun run scripts/clean.mjs",
"prepublishOnly": "bun run scripts/build.mjs && bun run scripts/prepublish-check.js",
"format": "prettier --write \"*.{md,json,yml,yaml}\" \".github/**/*.{md,yml,yaml}\" \"apps/**/*.{ts,tsx,js,jsx,json,md,css,html}\" \"packages/**/*.{ts,tsx,js,jsx,json,md}\" \"scripts/**/*.{ts,tsx,js,jsx,mjs,cjs,json}\" \"docs/**/*.{md,json}\"",
"format:check": "prettier --check \"*.{md,json,yml,yaml}\" \".github/**/*.{md,yml,yaml}\" \"apps/**/*.{ts,tsx,js,jsx,json,md,css,html}\" \"packages/**/*.{ts,tsx,js,jsx,json,md}\" \"scripts/**/*.{ts,tsx,js,jsx,mjs,cjs,json}\" \"docs/**/*.{md,json}\"",
"format": "prettier --write \"*.{md,json,yml,yaml}\" \".github/**/*.{md,yml,yaml}\" \"test/**/*.{ts,tsx}\" \"apps/**/*.{ts,tsx,js,jsx,json,md,css,html}\" \"packages/**/*.{ts,tsx,js,jsx,json,md}\" \"scripts/**/*.{ts,tsx,js,jsx,mjs,cjs,json}\" \"docs/**/*.{md,json}\"",
"format:check": "prettier --check \"*.{md,json,yml,yaml}\" \".github/**/*.{md,yml,yaml}\" \"test/**/*.{ts,tsx}\" \"apps/**/*.{ts,tsx,js,jsx,json,md,css,html}\" \"packages/**/*.{ts,tsx,js,jsx,json,md}\" \"scripts/**/*.{ts,tsx,js,jsx,mjs,cjs,json}\" \"docs/**/*.{md,json}\"",
"architecture:check": "node scripts/check-architecture.mjs",
"security:audit": "bun audit --audit-level=high",
"test": "bun test",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { existsSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type { ChildProcess } from 'node:child_process'
import { escapeSocatPath } from '#runtime/shell/socat'

export type LinuxSandboxBridge = {
httpSocketPath: string
Expand Down Expand Up @@ -47,7 +48,7 @@ export async function startLinuxSandboxBridge(args: {
safeUnlink(socksSocketPath)

const httpArgs = [
`UNIX-LISTEN:${httpSocketPath},fork,reuseaddr`,
`UNIX-LISTEN:${escapeSocatPath(httpSocketPath)},fork,reuseaddr`,
`TCP:localhost:${args.hostHttpProxyPort},keepalive,keepidle=10,keepintvl=5,keepcnt=3`,
]
const httpBridgeProcess = spawn('socat', httpArgs, { stdio: 'ignore' })
Expand All @@ -56,7 +57,7 @@ export async function startLinuxSandboxBridge(args: {
}

const socksArgs = [
`UNIX-LISTEN:${socksSocketPath},fork,reuseaddr`,
`UNIX-LISTEN:${escapeSocatPath(socksSocketPath)},fork,reuseaddr`,
`TCP:localhost:${args.hostSocksProxyPort},keepalive,keepidle=10,keepintvl=5,keepcnt=3`,
]
const socksBridgeProcess = spawn('socat', socksArgs, { stdio: 'ignore' })
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/test/e2e/inkTestHarness.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ export function createInkTestHarness(
stdin: stdin as unknown as NodeJS.ReadStream,
stdout: stdout as unknown as NodeJS.WriteStream,
exitOnCtrlC: false,
// Ink normally buffers CI output until unmount. These interaction tests
// need every intermediate frame, including while running on CI.
debug: true,
})

return {
Expand Down
Loading
Loading