Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

nushell/tests/pi.test.nu

Raw
use std/assert
use ../modules/pi_names.nu

const module_path = path self ../modules/pi.nu

# Replace only terminal ownership; exercise the actual module's discovery and widgets.
def render [home: path, agent: string, sessions: string, output: path, --fails] {
    let code = r#'
def 'tui run' [--refresh: duration, hook?: closure] {
    tui debug $hook --size [160 12] --keys [down enter]
    | to json
    | save --force $env.PI_TEST_RESULT
}
use '__MODULE_PATH__'
pi sessions --global
'# | str replace '__MODULE_PATH__' $module_path
    let result = with-env {
        HOME: $home
        USERPROFILE: $home
        PI_CODING_AGENT_DIR: $agent
        PI_CODING_AGENT_SESSION_DIR: $sessions
        PI_TEST_RESULT: $output
    } { ^($nu.current-exe) --no-config-file -c $code | complete }
    if $fails {
        assert ($result.exit_code != 0) 'Invalid selected settings must fail, not fall back'
        return $result
    }
    assert equal $result.exit_code 0 $result.stderr
    open $output
}

def fixture [root: path, relative: string, id: string, --parent: string = '', --cwd: string = ''] {
    let file = $root | path join $relative
    mkdir ($file | path dirname)
    {type: session, version: 3, id: $id, timestamp: '2026-01-01T00:00:00Z', cwd: (if $cwd == '' { $"/projects/($id)" } else { $cwd }), parentSession: (if $parent == '' { null } else { $parent })}
    | to json --raw
    | save $file
}

def hierarchy-views [root: path, output: path, --open-child, --local, --cwd: string = '', --inputs: list = []] {
    mkdir $output
    let keys = if ($inputs | is-not-empty) { $inputs } else if $open_child { [
        [/ 'type:ROOT_PARENT' tab right]
        [/ 'type:CHILD_ALPHA' tab enter]
        [left]
        []
    ] } else { [
        [/ 'type:ROOT_PARENT' tab right]
        [/ 'type:CHILD_ALPHA' tab right]
        [left]
        [left]
        []
    ] }
    let code = r#'
cd $env.PI_PICKER_CWD
$env.PI_PICKER_STEP = '0'
def 'term size' [] { {columns: 80 rows: 24} }
def 'input listen' [--timeout: duration] { {type: key code: q modifiers: []} }
def --env 'tui run' [--refresh: duration, hook?: closure] {
    let ui = $in
    let index = $env.PI_PICKER_STEP | into int
    let inputs = $env.PI_PICKER_KEYS | from json
    if $index >= ($inputs | length) { error make {msg: 'Unexpected extra picker'} }
    let view = $ui | tui debug $hook --size [180 16] --keys ($inputs | get $index)
    $view | to json | save ($env.PI_PICKER_OUTPUT | path join ($index | into string | $in + '.json'))
    $env.PI_PICKER_STEP = ($index + 1 | into string)
    $view
}
use '__MODULE_PATH__'
pi sessions __GLOBAL__
'# | str replace '__MODULE_PATH__' $module_path | str replace '__GLOBAL__' (if $local { '' } else { '--global' })
    let result = with-env {PI_CODING_AGENT_SESSION_DIR: $root, PI_PICKER_KEYS: ($keys | to json --raw), PI_PICKER_OUTPUT: $output, PI_PICKER_CWD: (if $cwd == '' { $env.PWD } else { $cwd })} {
        ^($nu.current-exe) --no-config-file -c $code | complete
    }
    assert equal $result.exit_code 0 $result.stderr
    {
        views: (0..(($keys | length) - 1) | each {|index| open ($output | path join $"($index).json") })
        reader_entered: ($result.stdout | str contains $'(char --integer 27)[?1049h')
        reader_left: ($result.stdout | str contains $'(char --integer 27)[?1049l')
    }
}

let temp = mktemp --directory --tmpdir pi-nu-test.XXXXXX
try {
    # Real worker -> RAM mailbox -> refresh -> native rendered session column.
    let names_root = $temp | path join names
    fixture $names_root renamed.jsonl NAMED
    let named = $names_root | path join renamed.jsonl
    [
        {type: message message: {role: user content: [{type: text text: 'First user excerpt'}]}}
        {type: session_info name: 'Old title'}
        {type: session_info name: 'Latest title'}
        {type: session_info name: 42}
        {type: tool_result payload: {type: session_info name: 'Nested fake'}}
        {type: message message: {role: assistant content: [{type: thinking thinking: 'Never a title'}]}}
    ] | each { to json --raw } | str join (char nl) | (char nl) + $in + (char nl) | save --append $named
    assert equal (pi_names read-name $named NAMED) 'Latest title'
    '{"type":"session_info","name":""}' | save --append $named
    assert equal (pi_names read-name $named NAMED) 'First user excerpt'
    (char nl) + '{"type":"session_info","name":"Final\nTitle  
"}' | save --append $named
    assert equal (pi_names read-name $named NAMED) 'Final Title'
    let first_cache = pi_names cached-name [] {path: $named id: NAMED}
    assert (not $first_cache.hit)
    assert (pi_names cached-name $first_cache.cache {path: $named id: NAMED}).hit
    (char nl) + '{"type":"session_info","name":"Rendered title"}' | save --append $named
    let changed_cache = pi_names cached-name $first_cache.cache {path: $named id: NAMED}
    assert (not $changed_cache.hit)
    assert equal $changed_cache.name 'Rendered title'
    let files_before = glob ($names_root | path join '*')
    let worker = pi_names start
    try {
        let gone = $names_root | path join gone.jsonl
        fixture $names_root gone.jsonl GONE
        let row = {id: NAMED path: $named cwd: match modified: (date now) session: NAMED children: 0 parentOutsideScope: false}
        let lost = $row | update path $gone | update id GONE | update session GONE
        pi_names mailbox-write $worker.table view 1 [$lost $row]
        rm $gone
        mut rendered: any = null
        for attempt in 1..100 {
            let packet = pi_names refresh $worker.table 1 {focused: query values: {query: ''} selected: $row}
            if $packet != null {
                let view = $packet | tui search --id query --fuzzy --columns [session cwd id path] --bind / | tui table --id sessions --focus --columns [session] | tui debug --keys [down]
                if ($view.screen | str contains 'Rendered title') { $rendered = $view; break }
            }
            sleep 20ms
        }
        assert ($rendered != null) 'Worker must survive a removed file and render the next name'
        assert equal $rendered.selected.path $named
        assert equal $rendered.selected.id NAMED

        let lazy_root = $temp | path join lazy
        let lazy_rows = 0..<40 | each {|index|
            let id = $'ROW_($index)'
            fixture $lazy_root $'($index).jsonl' $id
            let path = $lazy_root | path join $'($index).jsonl'
            (char nl) + '{"type":"session_info","name":"Bounded title"}' | save --append $path
            $row | update id $id | update session $id | update path $path
        }
        pi_names mailbox-write $worker.table selected 0 null
        pi_names mailbox-write $worker.table view 2 $lazy_rows
        mut latest = $lazy_rows
        for attempt in 1..150 {
            let packet = pi_names refresh $worker.table 2 {focused: query values: {query: ''} selected: $lazy_rows.0}
            if $packet != null { $latest = $packet }
            if ($latest | first 32 | all {|row| $row.session == 'Bounded title' }) { break }
            sleep 20ms
        }
        assert ($latest | first 32 | all {|row| $row.session == 'Bounded title' })
        assert equal $latest.39.session ROW_39 'Initial prefetch must not read every log'
        assert equal ($latest | get path) ($lazy_rows | get path)
        let first_priority = pi_names refresh $worker.table 2 {focused: query values: {query: ''} selected: $lazy_rows.39}
        if $first_priority != null { $latest = $first_priority }
        for attempt in 1..100 {
            let packet = pi_names refresh $worker.table 2 {focused: query values: {query: ''} selected: $lazy_rows.39}
            if $packet != null { $latest = $packet }
            if $latest.39.session == 'Bounded title' { break }
            sleep 20ms
        }
        assert equal $latest.39.session 'Bounded title' 'Selecting beyond prefetch must prioritize its name'

        # A delayed title would add a row before the current selection under this fixed query.
        let other = $row | update path /synthetic/other | update id OTHER | update cwd elsewhere | update session OTHER
        let fixed = [$other $row] | tui search --id query --bind / --fuzzy --columns [session cwd] | tui table --id sessions --focus | tui debug --keys [/ 'type:match' tab]
        assert equal $fixed.focused sessions
        assert equal $fixed.selected.path $named
        let old_seq = pi_names mailbox-read $worker.table result | get seq
        pi_names mailbox-write $worker.table result ($old_seq + 1) {version: 1 rows: [($other | update session match) ($row | update session 'Rendered title')]}
        assert equal (pi_names refresh $worker.table 1 $fixed) null
        assert equal $fixed.selected.path $named
        let editing = $fixed | update focused query
        let applied = pi_names refresh $worker.table 1 $editing
        assert equal ($applied | get path) [/synthetic/other $named] 'Lazy updates never reorder rows'
        let fuzzy = $applied | tui search --id query --bind / --fuzzy --columns [session] | tui table --id sessions --focus | tui debug --keys [/ 'type:Rndttl' tab]
        assert equal $fuzzy.selected.path $named
    } catch {|err|
        pi_names stop $worker
        error make $err
    }
    pi_names stop $worker
    assert equal (glob ($names_root | path join '*')) $files_before 'Names must create no disk cache'
    assert (not (job list | any {|job| $job.id == $worker.worker }))

    let invalid = $names_root | path join invalid.jsonl
    [
        '{"type":"tool_result","payload":{"type":"session_info","name":"nested"}}'
        '{"type":"message","message":{"role":"assistant","content":"escaped \\"type\\":\\"session_info\\",\\"name\\":\\"fake\\""}}'
        '{broken "type":"session_info"}'
        '{"type":"session_info","name":false}'
    ] | str join (char nl) | save $invalid
    assert equal (pi_names read-name $invalid 1234567890123456) '123456789012'
    '{"type":"message","message":{"content":[{"type":"text","text":"Hello"}],"role":"user"}}' | save --force $invalid
    assert equal (pi_names read-name $invalid fallback) Hello
    (char nl) + '{"metadata":{"nested":[]},"type":"session_info","name":"Reordered root"}' | save --append $invalid
    assert equal (pi_names read-name $invalid fallback) 'Reordered root'
    let home = $temp | path join home
    let default_root = $home | path join .pi agent sessions
    fixture $default_root 'project/default.jsonl' default
    let output = $temp | path join render.json
    let default_view = render $home '' '' $output
    assert equal $default_view.rows 1
    assert (not ($default_view.screen | str contains '[:'))
    assert (not ($default_view.screen | str contains 'focus:'))
    assert (not ($default_view.screen | str contains 'rows:'))
    assert ($default_view.screen | str contains '/projects/default')

    let settings_root = $temp | path join 'settings sessions'
    fixture $settings_root 'project/settings.jsonl' settings
    {sessionDir: $settings_root} | save ($home | path join .pi agent settings.json)
    let settings_view = render $home '' '' $output
    assert equal $settings_view.rows 1
    assert ($settings_view.screen | str contains '/projects/settings')

    let agent = $temp | path join 'custom agent'
    fixture ($agent | path join sessions) 'project/agent.jsonl' agent
    let agent_view = render $home $agent '' $output
    assert equal $agent_view.rows 1
    assert ($agent_view.screen | str contains '/projects/agent')

    {sessionDir: $settings_root} | save ($agent | path join settings.json)
    let custom_settings_view = render $home $agent '' $output
    assert equal $custom_settings_view.rows 1
    assert ($custom_settings_view.screen | str contains '/projects/settings')

    let root = $temp | path join 'session root'
    fixture $root 'first/one.jsonl' one
    fixture $root 'second/nested/two.jsonl' two
    'not json' | save ($root | path join broken.jsonl)
    '{"type":"message"}' | save ($root | path join other.jsonl)
    let view = render $home $agent $root $output
    assert equal $view.rows 2
    assert ($view.screen | str contains '/projects/one')
    assert ($view.screen | str contains '/projects/two')
    assert ($view.selected.id in [one two])
    assert equal $view.action submit

    # Env takes priority without even parsing lower-priority settings.
    'invalid json' | save --force ($agent | path join settings.json)
    let env_view = render $home $agent $root $output
    assert equal $env_view.rows 2
    let invalid_settings = render $home $agent '' $output --fails
    assert ($invalid_settings.stderr | is-not-empty) 'Invalid selected settings must report a diagnostic'

    # Missing sessionDir falls back to this agent's default sessions directory.
    {theme: example} | save --force ($agent | path join settings.json)
    let fallback_view = render $home $agent '' $output
    assert equal $fallback_view.rows 1
    assert ($fallback_view.screen | str contains '/projects/agent')

    let empty = $temp | path join empty
    mkdir $empty
    let empty_view = render $home $agent $empty $output
    assert equal $empty_view.rows 0
    let missing = $temp | path join missing
    let missing_view = render $home $agent $missing $output
    assert equal $missing_view.rows 0
    assert (not ($missing | path exists))

    # Inter-file parentSession lineage is distinct from in-file message parentId.
    let family = $temp | path join 'family α sessions'
    let parent = $family | path join parent.jsonl
    let child = $family | path join child-alpha.jsonl
    fixture $family parent.jsonl ROOT_PARENT
    fixture $family child-alpha.jsonl CHILD_ALPHA --parent $parent
    fixture $family child-beta.jsonl CHILD_BETA --parent parent.jsonl
    fixture $family grandchild.jsonl GRAND_CHILD --parent $child
    fixture $family orphan.jsonl ORPHAN --parent ($family | path join missing.jsonl)
    fixture $family self.jsonl SELF --parent ($family | path join self.jsonl)
    fixture $family cycle-a.jsonl CYCLE_A --parent ($family | path join cycle-b.jsonl)
    fixture $family cycle-b.jsonl CYCLE_B --parent ($family | path join cycle-a.jsonl)
    let listing = with-env {PI_CODING_AGENT_SESSION_DIR: $family} {
        ^($nu.current-exe) --no-config-file -c $"use '($module_path)'; pi sessions list --global | to json --raw" | complete
    }
    assert equal $listing.exit_code 0 $listing.stderr
    let family_rows = $listing.stdout | from json
    assert equal ($family_rows | length) 8
    assert equal ($family_rows | where id == ROOT_PARENT | first | get children) 2
    assert equal ($family_rows | where id == CHILD_ALPHA | first | get children) 1
    assert equal ($family_rows | where id == CHILD_BETA | first | get parent) $parent
    assert equal ($family_rows | where id == GRAND_CHILD | first | get parent) $child
    assert equal ($family_rows | where id == ORPHAN | first | get parent) null
    assert equal ($family_rows | where id == SELF | first | get parent) null
    assert equal ($family_rows | where {|row| $row.id in [CYCLE_A CYCLE_B] and $row.parent == null } | length) 1
    for row in $family_rows {
        mut path = $row.path
        for step in 1..9 {
            if $path == null { break }
            let current = $path
            $path = ($family_rows | where path == $current | first | get parent)
        }
        assert equal $path null 'Every listed session must be reachable from a visible root'
    }
    let views = hierarchy-views $family ($temp | path join hierarchy-views) | get views
    assert equal $views.0.selected.navigation children
    assert equal $views.0.selected.path $parent
    assert (not ($views.0.screen | str contains CHILD_ALPHA))
    assert (not ($views.0.screen | str contains GRAND_CHILD))
    assert equal $views.1.selected.navigation children
    assert equal $views.1.selected.path $child
    assert (not ($views.1.screen | str contains GRAND_CHILD))
    assert ($views.2.screen | str contains GRAND_CHILD)
    assert equal $views.2.selected.navigation up
    assert ($views.3.screen | str contains CHILD_BETA)
    assert (not ($views.3.screen | str contains GRAND_CHILD))
    assert equal $views.3.selected.navigation up
    assert ($views.4.screen | str contains ROOT_PARENT)
    assert ($views.4.screen | str contains ORPHAN)
    assert (not ($views.4.screen | str contains CHILD_ALPHA))
    let handoff = hierarchy-views $family ($temp | path join child-reader-views) --open-child
    assert equal $handoff.views.1.action submit
    assert equal $handoff.views.1.selected.path $child
    assert $handoff.reader_entered 'Enter on a child must enter the actual reader'
    assert $handoff.reader_left 'Leaving the child reader must restore its terminal'
    assert ($handoff.views.2.screen | str contains CHILD_ALPHA)
    assert ($handoff.views.2.screen | str contains CHILD_BETA)
    assert (not ($handoff.views.2.screen | str contains GRAND_CHILD))
    assert equal $handoff.views.2.selected.navigation up
    assert ($handoff.views.3.screen | str contains ROOT_PARENT)

    # Visibility is exact launch cwd, independent of the one shared storage root.
    let store = $temp | path join shared-store
    let local = $temp | path join 'local α project'
    let foreign = $temp | path join foreign-project
    let nested = $local | path join nested
    let unused = $temp | path join unused-project
    mkdir $local $foreign $nested $unused
    let local_parent = $store | path join local-root.jsonl
    let foreign_parent = $store | path join foreign-root.jsonl
    fixture $store local-root.jsonl L_ROOT --cwd $local
    fixture $store local-child.jsonl L_CHILD --cwd $local --parent $local_parent
    fixture $store foreign-child.jsonl F_CHILD --cwd $foreign --parent $local_parent
    fixture $store foreign-root.jsonl F_ROOT --cwd $foreign
    fixture $store cross-child.jsonl L_CROSS --cwd $local --parent $foreign_parent
    fixture $store nested.jsonl NESTED --cwd $nested
    fixture $store dot.jsonl DOT_CWD --cwd ($local + '/.')
    let local_list = with-env {PI_CODING_AGENT_SESSION_DIR: $store, PI_TEST_CWD: $local} {
        ^($nu.current-exe) --no-config-file -c $"cd $env.PI_TEST_CWD; use '($module_path)'; pi sessions list | to json --raw" | complete
    }
    assert equal $local_list.exit_code 0 $local_list.stderr
    let local_rows = $local_list.stdout | from json
    assert equal ($local_rows | get id | sort) [L_CHILD L_CROSS L_ROOT]
    assert equal ($local_rows | where id == L_ROOT | first | get children) 1
    let cross = $local_rows | where id == L_CROSS | first
    assert equal $cross.parent $foreign_parent
    assert equal $cross.parentSession $foreign_parent
    assert equal $cross.scope_parent null
    assert $cross.parentOutsideScope
    assert ($cross.session | str contains '↳')
    let global_list = with-env {PI_CODING_AGENT_SESSION_DIR: $store, PI_TEST_CWD: $local} {
        ^($nu.current-exe) --no-config-file -c $"cd $env.PI_TEST_CWD; use '($module_path)'; pi sessions list --global | to json --raw" | complete
    }
    assert equal $global_list.exit_code 0 $global_list.stderr
    let global_rows = $global_list.stdout | from json
    assert equal ($global_rows | length) 7
    assert equal ($global_rows | where id == L_ROOT | first | get children) 2
    assert equal ($global_rows | where id == L_CROSS | first | get scope_parent) $foreign_parent
    assert (not ($global_rows | any {|row| $row.parentOutsideScope }))
    let modes = hierarchy-views $store ($temp | path join scope-views) --local --cwd $local --inputs [
        [/ 'type:L_ROOT' tab right]
        [ctrl+a]
        [/ 'type:L_ROOT' tab right]
        [/ ctrl+a]
        []
    ] | get views
    assert ($modes.0.screen | str contains 'Pi sessions · local')
    assert (not ($modes.0.screen | str contains F_ROOT))
    assert ($modes.1.screen | str contains 'Children · L_ROOT · local')
    assert ($modes.1.screen | str contains L_CHILD)
    assert (not ($modes.1.screen | str contains F_CHILD))
    assert equal $modes.1.selected.navigation scope
    assert ($modes.2.screen | str contains 'Pi sessions · global')
    assert ($modes.3.screen | str contains 'Children · L_ROOT · global')
    assert ($modes.3.screen | str contains L_CHILD)
    assert ($modes.3.screen | str contains F_CHILD)
    assert equal $modes.3.selected.navigation scope
    assert ($modes.4.screen | str contains 'Pi sessions · local')
    assert ($modes.4.screen | str contains L_CROSS)
    assert ($modes.4.screen | str contains 'parent outside scope')
    assert (not ($modes.4.screen | str contains F_ROOT))
    assert (not ($modes.4.screen | str contains NESTED))
    let empty_local = hierarchy-views $store ($temp | path join empty-local-views) --local --cwd $unused --inputs [[ctrl+a] []] | get views
    assert equal $empty_local.0.rows 0
    assert ($empty_local.1.screen | str contains 'Pi sessions · global')
    assert ($empty_local.1.screen | str contains F_ROOT)

    # A harmless executable records argv and returns a controllable failure.
    if $nu.os-info.name != 'windows' {
        let bin = $temp | path join bin
        mkdir $bin
        let executable = $bin | path join pi
        '#!/bin/sh
printf "%s\n" "$@"
exit "${PI_TEST_EXIT:-0}"
' | save $executable
        ^chmod +x $executable
        # Capture scope routing without contacting the real user systemd manager.
        let scope = $bin | path join systemd-run
        '#!/bin/sh
printf "%s\n" "$@" > "$PI_TEST_SCOPE_LOG"
while [ "$#" -gt 0 ]; do
    case "$1" in --*) shift ;; *) break ;; esac
done
exec "$@"
' | save $scope
        ^chmod +x $scope
        let scope_log = $temp | path join scope-args.txt
        let code = $"use '($module_path)'; pi install 'npm:example' --help -- 'a b' 0001 true"
        let result = with-env {PATH: ($env.PATH | prepend $bin), PI_TEST_SCOPE_LOG: $scope_log} {
            ^($nu.current-exe) --no-config-file -c $code | complete
        }
        assert equal $result.exit_code 0 $result.stderr
        assert equal ($result.stdout | lines) [install 'npm:example' --help -- 'a b' '0001' 'true']
        assert equal (open --raw $scope_log | lines) [--user --scope --same-dir --collect --quiet --slice=work.slice pi install 'npm:example' --help -- 'a b' '0001' 'true']
        let failed = with-env {PATH: ($env.PATH | prepend $bin), PI_TEST_EXIT: '17', PI_TEST_SCOPE_LOG: $scope_log} {
            ^($nu.current-exe) --no-config-file -c $code | complete
        }
        assert equal $failed.exit_code 17
    }
} catch {|err|
    rm --recursive --force $temp
    error make $err
}
rm --recursive --force $temp
print 'Pi session discovery, TUI rendering, and passthrough tests passed'