feat(node): CLI 어댑터 로직 개선 및 세션 워크스페이스 고도화를 통합 커밋한다
This commit is contained in:
parent
cd5425e89a
commit
6d558f194b
11 changed files with 450 additions and 72 deletions
|
|
@ -42,45 +42,50 @@ task=m-openai-workspace-agent-execution-contract/04+03_session_workspace_isolati
|
|||
|
||||
| 항목 | 완료 여부 |
|
||||
|------|---------|
|
||||
| [API-1] Make CLI Session Keys Workspace-Aware | [ ] |
|
||||
| [API-2] Preserve Clear Terminate And Session List Semantics | [ ] |
|
||||
| [API-1] Make CLI Session Keys Workspace-Aware | [x] |
|
||||
| [API-2] Preserve Clear Terminate And Session List Semantics | [x] |
|
||||
|
||||
## 구현 체크리스트
|
||||
|
||||
- [ ] predecessor `03+02_cli_agent_cwd`의 `complete.log`가 active 또는 archive 위치에 있는지 확인한다.
|
||||
- [ ] `sessionKey`가 workspace를 포함하도록 확장하고, empty workspace는 기존 no-workspace key와 label을 유지한다.
|
||||
- [ ] persistent, codex-exec, codex app-server, antigravity-print, opencode-sse executors가 workspace-aware key를 사용한다.
|
||||
- [ ] session list response가 workspace별 session을 구분할 수 있도록 structured `session.N.workspace`를 채우고, label 충돌을 피한다.
|
||||
- [ ] `TerminateSession(target, sessionID)`가 workspace-aware key 도입 후에도 기존 command로 명확히 동작하도록 처리한다. workspace가 없는 command에서는 같은 target/session의 workspace variants를 모두 종료하거나, 구현에서 더 안전한 명시 오류를 선택하고 테스트로 고정한다.
|
||||
- [ ] 같은 target/session이 workspace별로 분리되는 테스트와 기존 no-workspace 동작 회귀 테스트를 추가한다.
|
||||
- [ ] `go test -count=1 ./apps/node/internal/adapters/cli ./apps/node/internal/node`를 실행한다.
|
||||
- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
|
||||
- [x] predecessor `03+02_cli_agent_cwd`의 `complete.log`가 active 또는 archive 위치에 있는지 확인한다.
|
||||
- [x] `sessionKey`가 workspace를 포함하도록 확장하고, empty workspace는 기존 no-workspace key와 label을 유지한다.
|
||||
- [x] persistent, codex-exec, codex app-server, antigravity-print, opencode-sse executors가 workspace-aware key를 사용한다.
|
||||
- [x] session list response가 workspace별 session을 구분할 수 있도록 structured `session.N.workspace`를 채우고, label 충돌을 피한다.
|
||||
- [x] `TerminateSession(target, sessionID)`가 workspace-aware key 도입 후에도 기존 command로 명확히 동작하도록 처리한다. workspace가 없는 command에서는 같은 target/session의 workspace variants를 모두 종료하거나, 구현에서 더 안전한 명시 오류를 선택하고 테스트로 고정한다.
|
||||
- [x] 같은 target/session이 workspace별로 분리되는 테스트와 기존 no-workspace 동작 회귀 테스트를 추가한다.
|
||||
- [x] `go test -count=1 ./apps/node/internal/adapters/cli ./apps/node/internal/node`를 실행한다.
|
||||
- [x] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
|
||||
|
||||
## 코드리뷰 전용 체크리스트
|
||||
|
||||
> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다.
|
||||
> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다.
|
||||
|
||||
- [ ] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다.
|
||||
- [ ] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다.
|
||||
- [ ] active `CODE_REVIEW-*-G??.md`를 `code_review_local_G08_N.log`로 아카이브한다.
|
||||
- [ ] active `PLAN-*-G??.md`를 `plan_local_G08_M.log`로 아카이브한다.
|
||||
- [ ] `.gitignore`의 Agent-Ops 관리 block이 `agent-task/**/*.md`와 `agent-task/**/*.log`를 unignore하고 `agent-roadmap/current.md`를 ignore하는지 확인한다.
|
||||
- [ ] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다.
|
||||
- [ ] PASS이면 active task 디렉터리 `agent-task/m-openai-workspace-agent-execution-contract/04+03_session_workspace_isolation/`를 `agent-task/archive/YYYY/MM/m-openai-workspace-agent-execution-contract/04+03_session_workspace_isolation/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다.
|
||||
- [ ] PASS이고 task group이 `m-<milestone-slug>`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다.
|
||||
- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-openai-workspace-agent-execution-contract/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다.
|
||||
- [x] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다.
|
||||
- [x] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다.
|
||||
- [x] active `CODE_REVIEW-*-G??.md`를 `code_review_local_G08_N.log`로 아카이브한다.
|
||||
- [x] active `PLAN-*-G??.md`를 `plan_local_G08_M.log`로 아카이브한다.
|
||||
- [x] `.gitignore`의 Agent-Ops 관리 block이 `agent-task/**/*.md`와 `agent-task/**/*.log`를 unignore하고 `agent-roadmap/current.md`를 ignore하는지 확인한다.
|
||||
- [x] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다.
|
||||
- [x] PASS이면 active task 디렉터리 `agent-task/m-openai-workspace-agent-execution-contract/04+03_session_workspace_isolation/`를 `agent-task/archive/YYYY/MM/m-openai-workspace-agent-execution-contract/04+03_session_workspace_isolation/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다.
|
||||
- [x] PASS이고 task group이 `m-<milestone-slug>`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다.
|
||||
- [x] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-openai-workspace-agent-execution-contract/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다.
|
||||
- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-local-G08.md`와 `CODE_REVIEW-local-G08.md`를 작성하고 `complete.log`를 작성하지 않는다.
|
||||
- [ ] USER_REVIEW이면 `agent-ops/skills/common/code-review/templates/user-review-template.md` 기준으로 `USER_REVIEW.md`를 작성하고 active `PLAN-*.md`, `CODE_REVIEW-*.md`, `complete.log`를 남기지 않는다.
|
||||
- [ ] USER_REVIEW가 사용자 결정으로 완료/PASS 해소되면 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log`를 작성한 뒤 task directory를 archive로 이동한다.
|
||||
|
||||
## 계획 대비 변경 사항
|
||||
|
||||
_구현 에이전트가 계획과 다르게 구현한 부분을 이유와 함께 기록한다._
|
||||
- 계획의 검증 명령(중간/최종)을 그대로 실행했다. 대체 없음.
|
||||
- 계획 권장안인 "같은 target/sessionID의 모든 workspace variants 종료"를 채택했다. 더 안전한 명시 오류 대안은 택하지 않았다. terminate command가 workspace를 받지 않으므로, 같은 target/sessionID를 공유하는 모든 workspace 세션을 한 번에 종료하는 것이 기존 운영 UX(`/terminate-session`)와 일관되기 때문이다.
|
||||
- `sessionListEntry.label()`은 workspace가 없으면 기존 `mode:target/sessionID` 형식을 그대로 유지하고, workspace가 있을 때만 `#<workspace>` suffix를 붙여 variant 충돌을 막았다. 기존 no-workspace label 회귀를 피하기 위함이다.
|
||||
|
||||
## 주요 설계 결정
|
||||
|
||||
_구현 에이전트가 주요 설계 결정 사항을 기록한다._
|
||||
- `sessionKey`에 `workspace string` 필드를 추가하고, 모든 executor가 공통 helper `newSessionKey(spec)`로 key를 만든다. helper는 `cliTargetName`, `normalizeSessionID`, 기존 `workspaceDir`(trim) 정규화를 한곳에 모은다. empty/whitespace workspace는 `""`로 정규화되어 workspace 도입 이전 key와 동일하게 유지된다.
|
||||
- 5개 executor(persistent, codex-exec, codex app-server, antigravity-print, opencode-sse)가 동일하게 workspace-aware key를 사용한다. opencode는 `--dir` override가 있어도 세션 경계는 `spec.Workspace` 기준으로 둔다(profile args의 `--dir`는 target별 상수이므로 같은 target에서 분기되지 않음).
|
||||
- session list는 `sessionListEntry`에 `workspace`를 실어 `session.N.workspace` structured field로 노출한다. no-workspace 세션은 빈 문자열로 표시된다.
|
||||
- terminate-all-variants 종료는 각 executor map을 순회하며 `target`/`sessionID`가 일치하는 모든 key를 삭제하고, 프로세스 소유 executor(persistent/opencode/codex app-server)는 매칭된 각 세션의 close/kill을 수행한다. 첫 close 오류만 보고한다(기존 Stop 패턴과 동일).
|
||||
|
||||
## 사용자 리뷰 요청
|
||||
|
||||
|
|
@ -114,24 +119,45 @@ _구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후
|
|||
### API-1 중간 검증
|
||||
```bash
|
||||
$ go test -count=1 ./apps/node/internal/adapters/cli
|
||||
(output)
|
||||
ok iop/apps/node/internal/adapters/cli 46.674s
|
||||
```
|
||||
|
||||
### API-2 중간 검증
|
||||
```bash
|
||||
$ go test -count=1 ./apps/node/internal/adapters/cli ./apps/node/internal/node
|
||||
(output)
|
||||
ok iop/apps/node/internal/adapters/cli 46.674s
|
||||
ok iop/apps/node/internal/node 0.124s
|
||||
```
|
||||
|
||||
### 최종 검증
|
||||
```bash
|
||||
$ go test -count=1 ./apps/node/internal/adapters/cli ./apps/node/internal/node
|
||||
(output)
|
||||
ok iop/apps/node/internal/adapters/cli 46.822s
|
||||
ok iop/apps/node/internal/node 0.122s
|
||||
|
||||
$ ./scripts/e2e-smoke.sh
|
||||
(output)
|
||||
{"level":"info",...,"caller":"cli/cli.go:240","msg":"cli adapter: persistent session started","target":"fake-cli"}
|
||||
[node-event] start run_id=manual-1781351173680754885
|
||||
[node-message] IOP_E2E_THANKS_FORMAL
|
||||
[node-event] complete run_id=manual-1781351173680754885 detail="idle-timeout"
|
||||
[node-event] start run_id=manual-1781351174899413927
|
||||
[node-message] IOP_E2E_PING_BASIC
|
||||
[node-event] complete run_id=manual-1781351174899413927 detail="idle-timeout"
|
||||
[node-event] start run_id=manual-1781351176536202844
|
||||
[node-message] IOP_E2E_STATUS_OK
|
||||
[node-event] complete run_id=manual-1781351176536202844 detail="idle-timeout"
|
||||
[node-event] ... SESSION_LIST / TERMINATE_SESSION 처리
|
||||
[e2e] Auxiliary smoke test PASSED.
|
||||
[e2e] Completion still requires scripts/dev/edge.sh + scripts/dev/node.sh user-flow verification.
|
||||
```
|
||||
|
||||
추가 신규 테스트(focused):
|
||||
```bash
|
||||
$ go test -count=1 -run 'Workspace|SessionKey|TerminateSession|HandleSessionList' ./apps/node/internal/adapters/cli
|
||||
ok iop/apps/node/internal/adapters/cli 2.647s
|
||||
```
|
||||
신규 테스트: `TestCLISameSessionDifferentWorkspaceIsolated`, `TestCLITerminateSessionStopsAllWorkspaceVariants`(blackbox), `TestHandleSessionList_WorkspaceVariantsDistinguished`, `TestHandleSessionList_NoWorkspaceHasEmptyWorkspaceField`, `TestSessionKey_NormalizesWorkspaceAndSessionID`, `TestTerminateSession_RemovesAllWorkspaceVariants`(internal).
|
||||
|
||||
---
|
||||
|
||||
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section: completion table, implementation checklist, changes from plan, design decisions, and verification output?**
|
||||
|
|
@ -151,3 +177,23 @@ $ ./scripts/e2e-smoke.sh
|
|||
| 사용자 리뷰 요청 | Implementing agent | Keep `상태: 없음` unless user input is required to proceed. |
|
||||
| 리뷰어를 위한 체크포인트 | Fixed at stub creation | Review focus areas from the plan. |
|
||||
| 검증 결과 | Implementing agent | Paste actual stdout/stderr for the commands above. |
|
||||
|
||||
## 코드리뷰 결과
|
||||
|
||||
- 종합 판정: PASS
|
||||
- 차원별 평가:
|
||||
- correctness: Pass
|
||||
- completeness: Pass
|
||||
- test coverage: Pass
|
||||
- API contract: Pass
|
||||
- code quality: Pass
|
||||
- plan deviation: Pass
|
||||
- verification trust: Pass
|
||||
- 발견된 문제: 없음
|
||||
- 다음 단계: PASS이므로 `complete.log` 작성 후 task directory를 archive로 이동한다. `m-openai-workspace-agent-execution-contract` 완료 이벤트 메타데이터를 보고하고, roadmap 수정은 code-review에서 수행하지 않는다.
|
||||
|
||||
리뷰 메모:
|
||||
- `sessionKey`가 workspace를 포함하고 empty workspace는 기존 no-workspace key/label을 유지한다.
|
||||
- persistent, codex-exec, codex app-server, antigravity-print, opencode-sse executor가 `newSessionKey(spec)`와 workspace-aware list/terminate path를 사용한다.
|
||||
- `TerminateSession(target, sessionID)`는 workspace를 받지 않는 기존 command 계약을 유지하면서 같은 target/sessionID의 workspace variants를 모두 종료하도록 고정되었다.
|
||||
- 구현 에이전트 검증 출력과 별도로 리뷰에서 `go test -count=1 ./apps/node/internal/adapters/cli ./apps/node/internal/node`, focused workspace/session tests, `git diff --check`, `./scripts/e2e-smoke.sh`, `scripts/dev/edge.sh` + `scripts/dev/node.sh` repo 내부 edge-node 진단을 재실행해 통과를 확인했다.
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
# Complete - m-openai-workspace-agent-execution-contract/04+03_session_workspace_isolation
|
||||
|
||||
## 완료 일시
|
||||
|
||||
2026-06-13
|
||||
|
||||
## 요약
|
||||
|
||||
CLI logical session workspace isolation 작업을 1회 리뷰 루프로 검증했고 최종 판정은 PASS다.
|
||||
|
||||
## 루프 이력
|
||||
|
||||
| Plan | Review | Verdict | 메모 |
|
||||
|------|--------|---------|------|
|
||||
| `plan_local_G08_0.log` | `code_review_local_G08_0.log` | PASS | workspace-aware session key/list/terminate 구현, 신규 회귀 테스트, Go/package/smoke/full-cycle 진단 검증이 충족됨 |
|
||||
|
||||
## 구현/정리 내용
|
||||
|
||||
- CLI `sessionKey`에 normalized workspace를 포함해 같은 target/sessionID라도 workspace가 다르면 별도 logical session으로 분리했다.
|
||||
- persistent, codex-exec, codex app-server, antigravity-print, opencode-sse executor가 workspace-aware key와 session list snapshot을 사용하도록 정리했다.
|
||||
- workspace를 받지 않는 `TerminateSession(target, sessionID)` command는 같은 target/sessionID의 모든 workspace variants를 종료하도록 동작을 고정했다.
|
||||
- session list response에 `session.N.workspace` structured field를 추가하고, workspace가 있는 session label은 suffix로 구분되도록 했다.
|
||||
- workspace 분리, no-workspace regression, session list workspace fields, terminate-all-variants 회귀 테스트를 추가했다.
|
||||
|
||||
## 최종 검증
|
||||
|
||||
- `go test -count=1 ./apps/node/internal/adapters/cli ./apps/node/internal/node` - PASS; `ok iop/apps/node/internal/adapters/cli 46.653s`, `ok iop/apps/node/internal/node 0.123s`
|
||||
- `go test -count=1 -run 'Workspace|SessionKey|TerminateSession|HandleSessionList' ./apps/node/internal/adapters/cli` - PASS; `ok iop/apps/node/internal/adapters/cli 2.676s`
|
||||
- `git diff --check` - PASS; 출력 없음
|
||||
- `./scripts/e2e-smoke.sh` - PASS; `[e2e] Auxiliary smoke test PASSED.`
|
||||
- `scripts/dev/edge.sh` + `scripts/dev/node.sh` repo 내부 edge-node 진단 - PASS; 임시 config/fake CLI로 `/nodes`, `/capabilities`, `/transport`, 같은 session 메시지 2회, `/sessions`, `/terminate-session` 확인. Edge에는 `IOP_E2E_DIRECT_ONE`, `IOP_E2E_DIRECT_TWO` payload와 complete event가 순서대로 표시되었고 node local payload와 일치했다.
|
||||
|
||||
## Roadmap Completion
|
||||
|
||||
- Milestone: `agent-roadmap/phase/automation-runtime-bridge/milestones/openai-workspace-agent-execution-contract.md`
|
||||
- Completed task ids:
|
||||
- `session-workspace`: PASS; evidence=`agent-task/archive/2026/06/m-openai-workspace-agent-execution-contract/04+03_session_workspace_isolation/plan_local_G08_0.log`, `agent-task/archive/2026/06/m-openai-workspace-agent-execution-contract/04+03_session_workspace_isolation/code_review_local_G08_0.log`; verification=`go test -count=1 ./apps/node/internal/adapters/cli ./apps/node/internal/node`, `go test -count=1 -run 'Workspace|SessionKey|TerminateSession|HandleSessionList' ./apps/node/internal/adapters/cli`, `git diff --check`, `./scripts/e2e-smoke.sh`, `scripts/dev/edge.sh + scripts/dev/node.sh`
|
||||
- Not completed task ids: 없음
|
||||
|
||||
## 잔여 Nit
|
||||
|
||||
- 없음
|
||||
|
||||
## 후속 작업
|
||||
|
||||
- 없음
|
||||
|
|
@ -60,7 +60,7 @@ func (e *antigravityExecutor) Execute(ctx context.Context, spec runtime.Executio
|
|||
|
||||
func (e *antigravityExecutor) resolveAntigravitySession(spec runtime.ExecutionSpec) (*antigravitySession, error) {
|
||||
target := cliTargetName(spec)
|
||||
key := sessionKey{target: target, sessionID: normalizeSessionID(spec.SessionID)}
|
||||
key := newSessionKey(spec)
|
||||
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
|
|
@ -81,20 +81,24 @@ func (e *antigravityExecutor) Sessions() []sessionListEntry {
|
|||
defer e.mu.Unlock()
|
||||
snaps := make([]sessionListEntry, 0, len(e.sessions))
|
||||
for k := range e.sessions {
|
||||
snaps = append(snaps, sessionListEntry{"antigravity-print", k.target, k.sessionID})
|
||||
snaps = append(snaps, sessionListEntry{"antigravity-print", k.target, k.sessionID, k.workspace})
|
||||
}
|
||||
return snaps
|
||||
}
|
||||
|
||||
func (e *antigravityExecutor) Terminate(ctx context.Context, target, sessionID string) (bool, error) {
|
||||
key := sessionKey{target: target, sessionID: normalizeSessionID(sessionID)}
|
||||
// Terminate removes every workspace variant of the given target/sessionID.
|
||||
func (e *antigravityExecutor) Terminate(_ context.Context, target, sessionID string) (bool, error) {
|
||||
sid := normalizeSessionID(sessionID)
|
||||
e.mu.Lock()
|
||||
_, ok := e.sessions[key]
|
||||
if ok {
|
||||
delete(e.sessions, key)
|
||||
defer e.mu.Unlock()
|
||||
removed := false
|
||||
for k := range e.sessions {
|
||||
if k.target == target && k.sessionID == sid {
|
||||
delete(e.sessions, k)
|
||||
removed = true
|
||||
}
|
||||
}
|
||||
e.mu.Unlock()
|
||||
return ok, nil
|
||||
return removed, nil
|
||||
}
|
||||
|
||||
func (e *antigravityExecutor) Stop(ctx context.Context) error {
|
||||
|
|
|
|||
|
|
@ -41,10 +41,24 @@ type cliOutput struct {
|
|||
markerLine string
|
||||
}
|
||||
|
||||
// sessionKey uniquely identifies a logical worker session.
|
||||
// sessionKey uniquely identifies a logical worker session. workspace is the
|
||||
// normalized workspace directory bound to the session; an empty workspace keeps
|
||||
// the historical no-workspace behavior and labels unchanged.
|
||||
type sessionKey struct {
|
||||
target string
|
||||
sessionID string
|
||||
workspace string
|
||||
}
|
||||
|
||||
// newSessionKey builds a workspace-aware session key from an execution spec.
|
||||
// An empty/whitespace workspace normalizes to "" so existing no-workspace
|
||||
// sessions keep the same key as before workspace support.
|
||||
func newSessionKey(spec runtime.ExecutionSpec) sessionKey {
|
||||
return sessionKey{
|
||||
target: cliTargetName(spec),
|
||||
sessionID: normalizeSessionID(spec.SessionID),
|
||||
workspace: workspaceDir(spec.Workspace),
|
||||
}
|
||||
}
|
||||
|
||||
type profileSession struct {
|
||||
|
|
@ -359,10 +373,19 @@ type sessionListEntry struct {
|
|||
mode string
|
||||
target string
|
||||
sessionID string
|
||||
workspace string
|
||||
}
|
||||
|
||||
// label returns a stable, human-readable identifier for the session. For
|
||||
// no-workspace sessions the format is unchanged ("mode:target/sessionID");
|
||||
// when a workspace is bound it is appended ("...#workspace") so workspace
|
||||
// variants of the same target/sessionID do not collide.
|
||||
func (e sessionListEntry) label() string {
|
||||
return e.mode + ":" + e.target + "/" + e.sessionID
|
||||
base := e.mode + ":" + e.target + "/" + e.sessionID
|
||||
if e.workspace == "" {
|
||||
return base
|
||||
}
|
||||
return base + "#" + e.workspace
|
||||
}
|
||||
|
||||
func (c *CLI) handleSessionList(req runtime.CommandRequest) runtime.CommandResponse {
|
||||
|
|
@ -385,6 +408,7 @@ func (c *CLI) handleSessionList(req runtime.CommandRequest) runtime.CommandRespo
|
|||
result[prefix+"mode"] = s.mode
|
||||
result[prefix+"target"] = s.target
|
||||
result[prefix+"session_id"] = s.sessionID
|
||||
result[prefix+"workspace"] = s.workspace
|
||||
}
|
||||
return runtime.CommandResponse{
|
||||
RequestID: req.RequestID,
|
||||
|
|
|
|||
|
|
@ -493,6 +493,85 @@ func TestHandleSessionList_PopulatedSnapshot(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestHandleSessionList_WorkspaceVariantsDistinguished(t *testing.T) {
|
||||
c := New(config.CLIConf{}, nil)
|
||||
// Same target/sessionID, two different workspaces, plus a no-workspace session.
|
||||
c.persistentExecutor.sessions[sessionKey{target: "claude", sessionID: "default"}] = &profileSession{}
|
||||
c.persistentExecutor.sessions[sessionKey{target: "claude", sessionID: "default", workspace: "/ws/a"}] = &profileSession{}
|
||||
c.persistentExecutor.sessions[sessionKey{target: "claude", sessionID: "default", workspace: "/ws/b"}] = &profileSession{}
|
||||
|
||||
resp := c.handleSessionList(runtime.CommandRequest{
|
||||
RequestID: "req-ws",
|
||||
Type: runtime.CommandTypeSessionList,
|
||||
})
|
||||
|
||||
if resp.Result["count"] != "3" {
|
||||
t.Fatalf("count: got %q want %q", resp.Result["count"], "3")
|
||||
}
|
||||
// Labels must be distinct so the three variants do not collide.
|
||||
want := "persistent:claude/default,persistent:claude/default#/ws/a,persistent:claude/default#/ws/b"
|
||||
if got := resp.Result["sessions"]; got != want {
|
||||
t.Fatalf("sessions: got %q want %q", got, want)
|
||||
}
|
||||
|
||||
// Sorted by label: no-workspace first, then #/ws/a, then #/ws/b.
|
||||
wantEntries := []struct{ label, workspace string }{
|
||||
{"persistent:claude/default", ""},
|
||||
{"persistent:claude/default#/ws/a", "/ws/a"},
|
||||
{"persistent:claude/default#/ws/b", "/ws/b"},
|
||||
}
|
||||
for i, we := range wantEntries {
|
||||
prefix := fmt.Sprintf("session.%d.", i)
|
||||
if got := resp.Result[prefix+"label"]; got != we.label {
|
||||
t.Errorf("%slabel: got %q want %q", prefix, got, we.label)
|
||||
}
|
||||
if got := resp.Result[prefix+"workspace"]; got != we.workspace {
|
||||
t.Errorf("%sworkspace: got %q want %q", prefix, got, we.workspace)
|
||||
}
|
||||
if got := resp.Result[prefix+"target"]; got != "claude" {
|
||||
t.Errorf("%starget: got %q want %q", prefix, got, "claude")
|
||||
}
|
||||
if got := resp.Result[prefix+"session_id"]; got != "default" {
|
||||
t.Errorf("%ssession_id: got %q want %q", prefix, got, "default")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleSessionList_NoWorkspaceHasEmptyWorkspaceField(t *testing.T) {
|
||||
c := New(config.CLIConf{}, nil)
|
||||
c.persistentExecutor.sessions[sessionKey{target: "claude", sessionID: "default"}] = &profileSession{}
|
||||
|
||||
resp := c.handleSessionList(runtime.CommandRequest{Type: runtime.CommandTypeSessionList})
|
||||
|
||||
if got := resp.Result["session.0.label"]; got != "persistent:claude/default" {
|
||||
t.Fatalf("label: got %q want %q", got, "persistent:claude/default")
|
||||
}
|
||||
if got, ok := resp.Result["session.0.workspace"]; !ok || got != "" {
|
||||
t.Fatalf("workspace: got %q present=%v want empty string", got, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionKey_NormalizesWorkspaceAndSessionID(t *testing.T) {
|
||||
key := newSessionKey(runtime.ExecutionSpec{
|
||||
Target: "claude",
|
||||
Workspace: " /ws/a ",
|
||||
})
|
||||
if key.target != "claude" {
|
||||
t.Errorf("target: got %q want %q", key.target, "claude")
|
||||
}
|
||||
if key.sessionID != runtime.DefaultSessionID {
|
||||
t.Errorf("sessionID: got %q want default %q", key.sessionID, runtime.DefaultSessionID)
|
||||
}
|
||||
if key.workspace != "/ws/a" {
|
||||
t.Errorf("workspace: got %q want trimmed %q", key.workspace, "/ws/a")
|
||||
}
|
||||
|
||||
empty := newSessionKey(runtime.ExecutionSpec{Target: "claude", Workspace: " "})
|
||||
if empty.workspace != "" {
|
||||
t.Errorf("blank workspace should normalize to empty, got %q", empty.workspace)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleSessionList_SlashInSessionID(t *testing.T) {
|
||||
c := New(config.CLIConf{}, nil)
|
||||
c.persistentExecutor.sessions[sessionKey{target: "claude", sessionID: "team/a/b"}] = &profileSession{}
|
||||
|
|
@ -658,6 +737,39 @@ func TestTerminateSession_CodexAppServerRemovesFromList(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestTerminateSession_RemovesAllWorkspaceVariants(t *testing.T) {
|
||||
c := New(config.CLIConf{
|
||||
Profiles: map[string]config.CLIProfileConf{
|
||||
"codex": {Mode: modeCodexExec},
|
||||
},
|
||||
}, nil)
|
||||
// Same target/sessionID across no-workspace and two workspaces.
|
||||
for _, ws := range []string{"", "/ws/a", "/ws/b"} {
|
||||
key := sessionKey{target: "codex", sessionID: "sess-1", workspace: ws}
|
||||
c.codexExecutor.sessions[key] = &codexExecSession{key: key}
|
||||
}
|
||||
// A different sessionID must survive termination.
|
||||
other := sessionKey{target: "codex", sessionID: "sess-2", workspace: "/ws/a"}
|
||||
c.codexExecutor.sessions[other] = &codexExecSession{key: other}
|
||||
|
||||
if err := c.TerminateSession(context.Background(), "codex", "sess-1"); err != nil {
|
||||
t.Fatalf("TerminateSession: %v", err)
|
||||
}
|
||||
|
||||
if len(c.codexExecutor.sessions) != 1 {
|
||||
t.Fatalf("expected only sess-2 to remain, got %d sessions", len(c.codexExecutor.sessions))
|
||||
}
|
||||
if _, ok := c.codexExecutor.sessions[other]; !ok {
|
||||
t.Fatal("sess-2 should not have been terminated")
|
||||
}
|
||||
|
||||
// Terminating a target/sessionID with no sessions must report not-found.
|
||||
err := c.TerminateSession(context.Background(), "codex", "missing")
|
||||
if err == nil {
|
||||
t.Fatal("expected error terminating unknown session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseProfileSession_PipeFallbackIdempotent(t *testing.T) {
|
||||
var mockCloseCalled int
|
||||
mockClose := func() error {
|
||||
|
|
|
|||
|
|
@ -298,7 +298,7 @@ func nestedString(params map[string]any, keys ...string) string {
|
|||
|
||||
func (e *codexAppServerExecutor) resolveCodexAppServerSession(ctx context.Context, spec runtime.ExecutionSpec, profile config.CLIProfileConf) (*codexAppServerSession, error) {
|
||||
target := cliTargetName(spec)
|
||||
key := sessionKey{target: target, sessionID: normalizeSessionID(spec.SessionID)}
|
||||
key := newSessionKey(spec)
|
||||
|
||||
e.mu.Lock()
|
||||
if sess, ok := e.sessions[key]; ok {
|
||||
|
|
@ -344,23 +344,29 @@ func (e *codexAppServerExecutor) Sessions() []sessionListEntry {
|
|||
defer e.mu.Unlock()
|
||||
snaps := make([]sessionListEntry, 0, len(e.sessions))
|
||||
for k := range e.sessions {
|
||||
snaps = append(snaps, sessionListEntry{modeCodexAppServer, k.target, k.sessionID})
|
||||
snaps = append(snaps, sessionListEntry{modeCodexAppServer, k.target, k.sessionID, k.workspace})
|
||||
}
|
||||
return snaps
|
||||
}
|
||||
|
||||
func (e *codexAppServerExecutor) Terminate(ctx context.Context, target, sessionID string) (bool, error) {
|
||||
key := sessionKey{target: target, sessionID: normalizeSessionID(sessionID)}
|
||||
// Terminate closes every workspace variant of the given target/sessionID.
|
||||
func (e *codexAppServerExecutor) Terminate(_ context.Context, target, sessionID string) (bool, error) {
|
||||
sid := normalizeSessionID(sessionID)
|
||||
e.mu.Lock()
|
||||
sess, ok := e.sessions[key]
|
||||
if ok {
|
||||
delete(e.sessions, key)
|
||||
var matched []*codexAppServerSession
|
||||
for k, sess := range e.sessions {
|
||||
if k.target == target && k.sessionID == sid {
|
||||
matched = append(matched, sess)
|
||||
delete(e.sessions, k)
|
||||
}
|
||||
}
|
||||
e.mu.Unlock()
|
||||
if !ok {
|
||||
if len(matched) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
closeCodexAppServerSession(sess)
|
||||
for _, sess := range matched {
|
||||
closeCodexAppServerSession(sess)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ func (e *codexExecutor) Execute(ctx context.Context, spec runtime.ExecutionSpec,
|
|||
|
||||
func (e *codexExecutor) resolveCodexExecSession(spec runtime.ExecutionSpec) (*codexExecSession, error) {
|
||||
target := cliTargetName(spec)
|
||||
key := sessionKey{target: target, sessionID: normalizeSessionID(spec.SessionID)}
|
||||
key := newSessionKey(spec)
|
||||
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
|
|
@ -67,20 +67,24 @@ func (e *codexExecutor) Sessions() []sessionListEntry {
|
|||
defer e.mu.Unlock()
|
||||
snaps := make([]sessionListEntry, 0, len(e.sessions))
|
||||
for k := range e.sessions {
|
||||
snaps = append(snaps, sessionListEntry{"codex-exec", k.target, k.sessionID})
|
||||
snaps = append(snaps, sessionListEntry{"codex-exec", k.target, k.sessionID, k.workspace})
|
||||
}
|
||||
return snaps
|
||||
}
|
||||
|
||||
func (e *codexExecutor) Terminate(ctx context.Context, target, sessionID string) (bool, error) {
|
||||
key := sessionKey{target: target, sessionID: normalizeSessionID(sessionID)}
|
||||
// Terminate removes every workspace variant of the given target/sessionID.
|
||||
func (e *codexExecutor) Terminate(_ context.Context, target, sessionID string) (bool, error) {
|
||||
sid := normalizeSessionID(sessionID)
|
||||
e.mu.Lock()
|
||||
_, ok := e.sessions[key]
|
||||
if ok {
|
||||
delete(e.sessions, key)
|
||||
defer e.mu.Unlock()
|
||||
removed := false
|
||||
for k := range e.sessions {
|
||||
if k.target == target && k.sessionID == sid {
|
||||
delete(e.sessions, k)
|
||||
removed = true
|
||||
}
|
||||
}
|
||||
e.mu.Unlock()
|
||||
return ok, nil
|
||||
return removed, nil
|
||||
}
|
||||
|
||||
func (e *codexExecutor) Stop(ctx context.Context) error {
|
||||
|
|
|
|||
|
|
@ -382,6 +382,124 @@ func TestCLITerminateSessionStopsOnlyTargetSession(t *testing.T) {
|
|||
_ = c.Stop(ctx)
|
||||
}
|
||||
|
||||
func TestCLISameSessionDifferentWorkspaceIsolated(t *testing.T) {
|
||||
testutil.RequireUnixShell(t)
|
||||
|
||||
cfg := config.CLIConf{
|
||||
Enabled: true,
|
||||
Profiles: map[string]config.CLIProfileConf{
|
||||
"pwd-echo": {
|
||||
Command: "sh",
|
||||
Args: []string{"-c", `while IFS= read -r line; do pwd; done`},
|
||||
Persistent: true,
|
||||
Terminal: false,
|
||||
ResponseIdleTimeoutMS: 200,
|
||||
},
|
||||
},
|
||||
}
|
||||
c := clipkg.New(cfg, zap.NewNop())
|
||||
ctx := context.Background()
|
||||
defer func() { _ = c.Stop(ctx) }()
|
||||
|
||||
wsA := t.TempDir()
|
||||
wsB := t.TempDir()
|
||||
|
||||
runIn := func(ws string) string {
|
||||
sink := &testutil.FakeSink{}
|
||||
if err := c.Execute(ctx, noderuntime.ExecutionSpec{
|
||||
RunID: "run-" + ws,
|
||||
Target: "pwd-echo",
|
||||
SessionID: "shared",
|
||||
Workspace: ws,
|
||||
Input: map[string]any{"prompt": "go"},
|
||||
}, sink); err != nil {
|
||||
t.Fatalf("execute in %q: %v", ws, err)
|
||||
}
|
||||
return testutil.CollectDeltas(sink.Events())
|
||||
}
|
||||
|
||||
outA := runIn(wsA)
|
||||
outB := runIn(wsB)
|
||||
|
||||
if !strings.Contains(outA, wsA) {
|
||||
t.Errorf("session for workspace A should run in %q, got %q", wsA, outA)
|
||||
}
|
||||
if !strings.Contains(outB, wsB) {
|
||||
t.Errorf("session for workspace B should run in %q, got %q", wsB, outB)
|
||||
}
|
||||
// Workspace A's session must not have run in workspace B's directory.
|
||||
if strings.Contains(outA, wsB) {
|
||||
t.Errorf("workspace A session leaked into workspace B dir %q: %q", wsB, outA)
|
||||
}
|
||||
|
||||
// Both workspace variants of the shared session must be present and distinct.
|
||||
resp, err := c.HandleCommand(ctx, noderuntime.CommandRequest{Type: noderuntime.CommandTypeSessionList})
|
||||
if err != nil {
|
||||
t.Fatalf("session list: %v", err)
|
||||
}
|
||||
if got := resp.Result["count"]; got != "2" {
|
||||
t.Fatalf("expected 2 isolated sessions, count = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLITerminateSessionStopsAllWorkspaceVariants(t *testing.T) {
|
||||
testutil.RequireUnixShell(t)
|
||||
|
||||
cfg := config.CLIConf{
|
||||
Enabled: true,
|
||||
Profiles: map[string]config.CLIProfileConf{
|
||||
"echo-ws": {
|
||||
Command: "sh",
|
||||
Args: []string{"-c", `while IFS= read -r line; do printf "reply:%s\n" "$line"; done`},
|
||||
Persistent: true,
|
||||
Terminal: false,
|
||||
ResponseIdleTimeoutMS: 200,
|
||||
},
|
||||
},
|
||||
}
|
||||
c := clipkg.New(cfg, zap.NewNop())
|
||||
ctx := context.Background()
|
||||
defer func() { _ = c.Stop(ctx) }()
|
||||
|
||||
wsA := t.TempDir()
|
||||
wsB := t.TempDir()
|
||||
|
||||
// Same target/sessionID across two workspaces.
|
||||
for _, ws := range []string{wsA, wsB} {
|
||||
sink := &testutil.FakeSink{}
|
||||
if err := c.Execute(ctx, noderuntime.ExecutionSpec{
|
||||
RunID: "run-create-" + ws,
|
||||
Target: "echo-ws",
|
||||
SessionID: "shared",
|
||||
Workspace: ws,
|
||||
Input: map[string]any{"prompt": "ping"},
|
||||
}, sink); err != nil {
|
||||
t.Fatalf("create session in %q: %v", ws, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The workspace-less terminate command must close every variant.
|
||||
if err := c.TerminateSession(ctx, "echo-ws", "shared"); err != nil {
|
||||
t.Fatalf("TerminateSession: %v", err)
|
||||
}
|
||||
|
||||
// Both workspace variants must now be gone (require-existing fails).
|
||||
for _, ws := range []string{wsA, wsB} {
|
||||
sink := &testutil.FakeSink{}
|
||||
err := c.Execute(ctx, noderuntime.ExecutionSpec{
|
||||
RunID: "run-after-" + ws,
|
||||
Target: "echo-ws",
|
||||
SessionID: "shared",
|
||||
Workspace: ws,
|
||||
SessionMode: noderuntime.SessionModeRequireExisting,
|
||||
Input: map[string]any{"prompt": "should-fail"},
|
||||
}, sink)
|
||||
if err == nil {
|
||||
t.Fatalf("workspace %q variant should be terminated, but require-existing succeeded", ws)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIStopStopsAllLogicalSessions(t *testing.T) {
|
||||
testutil.RequireUnixShell(t)
|
||||
|
||||
|
|
|
|||
|
|
@ -180,7 +180,7 @@ func (e *opencodeExecutor) Execute(ctx context.Context, spec runtime.ExecutionSp
|
|||
|
||||
func (e *opencodeExecutor) resolveOpencodeSession(ctx context.Context, spec runtime.ExecutionSpec, profile config.CLIProfileConf, opts opencodeRunOpts) (*opencodeSSESession, error) {
|
||||
target := cliTargetName(spec)
|
||||
key := sessionKey{target: target, sessionID: normalizeSessionID(spec.SessionID)}
|
||||
key := newSessionKey(spec)
|
||||
|
||||
e.mu.Lock()
|
||||
if sess, ok := e.sessions[key]; ok {
|
||||
|
|
@ -231,23 +231,30 @@ func (e *opencodeExecutor) Sessions() []sessionListEntry {
|
|||
defer e.mu.Unlock()
|
||||
snaps := make([]sessionListEntry, 0, len(e.sessions))
|
||||
for k := range e.sessions {
|
||||
snaps = append(snaps, sessionListEntry{"opencode-sse", k.target, k.sessionID})
|
||||
snaps = append(snaps, sessionListEntry{"opencode-sse", k.target, k.sessionID, k.workspace})
|
||||
}
|
||||
return snaps
|
||||
}
|
||||
|
||||
func (e *opencodeExecutor) Terminate(ctx context.Context, target, sessionID string) (bool, error) {
|
||||
key := sessionKey{target: target, sessionID: normalizeSessionID(sessionID)}
|
||||
// Terminate closes every workspace variant of the given target/sessionID,
|
||||
// killing each owned local server process.
|
||||
func (e *opencodeExecutor) Terminate(_ context.Context, target, sessionID string) (bool, error) {
|
||||
sid := normalizeSessionID(sessionID)
|
||||
e.mu.Lock()
|
||||
sess, ok := e.sessions[key]
|
||||
if ok {
|
||||
delete(e.sessions, key)
|
||||
var matched []*opencodeSSESession
|
||||
for k, sess := range e.sessions {
|
||||
if k.target == target && k.sessionID == sid {
|
||||
matched = append(matched, sess)
|
||||
delete(e.sessions, k)
|
||||
}
|
||||
}
|
||||
e.mu.Unlock()
|
||||
if !ok {
|
||||
if len(matched) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
closeOpencodeSession(sess)
|
||||
for _, sess := range matched {
|
||||
closeOpencodeSession(sess)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -311,7 +311,7 @@ func writePrompt(ctx context.Context, input io.Writer, prompt string, profile co
|
|||
// when SessionMode allows it.
|
||||
func (e *persistentExecutor) resolveSession(ctx context.Context, spec runtime.ExecutionSpec, profile config.CLIProfileConf) (*profileSession, error) {
|
||||
target := cliTargetName(spec)
|
||||
key := sessionKey{target: target, sessionID: normalizeSessionID(spec.SessionID)}
|
||||
key := newSessionKey(spec)
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
|
||||
|
|
@ -633,24 +633,35 @@ func (e *persistentExecutor) Sessions() []sessionListEntry {
|
|||
defer e.mu.Unlock()
|
||||
snaps := make([]sessionListEntry, 0, len(e.sessions))
|
||||
for k := range e.sessions {
|
||||
snaps = append(snaps, sessionListEntry{"persistent", k.target, k.sessionID})
|
||||
snaps = append(snaps, sessionListEntry{"persistent", k.target, k.sessionID, k.workspace})
|
||||
}
|
||||
return snaps
|
||||
}
|
||||
|
||||
// Terminate closes every workspace variant of the given target/sessionID. The
|
||||
// terminate command carries no workspace, so it terminates all logical sessions
|
||||
// that share the same target and session id regardless of bound workspace.
|
||||
func (e *persistentExecutor) Terminate(ctx context.Context, target, sessionID string) (bool, error) {
|
||||
key := sessionKey{target: target, sessionID: normalizeSessionID(sessionID)}
|
||||
sid := normalizeSessionID(sessionID)
|
||||
e.mu.Lock()
|
||||
sess, ok := e.sessions[key]
|
||||
if ok {
|
||||
delete(e.sessions, key)
|
||||
var matched []*profileSession
|
||||
for k, sess := range e.sessions {
|
||||
if k.target == target && k.sessionID == sid {
|
||||
matched = append(matched, sess)
|
||||
delete(e.sessions, k)
|
||||
}
|
||||
}
|
||||
e.mu.Unlock()
|
||||
if !ok {
|
||||
if len(matched) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
err := closeProfileSession(ctx, sess)
|
||||
return true, err
|
||||
var firstErr error
|
||||
for _, sess := range matched {
|
||||
if err := closeProfileSession(ctx, sess); err != nil && firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
}
|
||||
return true, firstErr
|
||||
}
|
||||
|
||||
func (e *persistentExecutor) Stop(ctx context.Context) error {
|
||||
|
|
|
|||
Loading…
Reference in a new issue