fix(kugetsu): use before/after session list to detect forked session

Compare session list before and after fork to reliably detect which
session is the newly created one. Avoids relying on parsing output
that may not contain session ID.
This commit is contained in:
shokollm
2026-03-29 20:25:41 +00:00
parent 636a41f41b
commit b422b33aa6

View File

@@ -249,35 +249,35 @@ cmd_start() {
local session_file="$(issue_ref_to_filename "$issue_ref").json" local session_file="$(issue_ref_to_filename "$issue_ref").json"
printf '{"type": "forked", "issue_ref": "%s", "opencode_session_id": "pending", "created_at": "%s", "state": "starting"}\n' \ local before_sessions=$(opencode session list 2>/dev/null | grep -oP '^ses_\w+' | sort)
"$issue_ref" "$(date -Iseconds)" > "$SESSIONS_DIR/$session_file" local before_set="${before_sessions//$'\n'/|}"
add_issue_to_index "$issue_ref" "$session_file"
echo "Forking session for '$issue_ref'..." echo "Forking session for '$issue_ref'..."
local fork_output
if [ "$DEBUG_MODE" = true ]; then if [ "$DEBUG_MODE" = true ]; then
fork_output=$(opencode run --fork --session "$base_session_id" "$message" 2>&1 | tee "$SESSIONS_DIR/$session_file.debug.log") opencode run --fork --session "$base_session_id" "$message" 2>&1 | tee "$SESSIONS_DIR/$session_file.debug.log"
else else
fork_output=$(opencode run --fork --session "$base_session_id" "$message" 2>&1) opencode run --fork --session "$base_session_id" "$message" 2>&1
fi fi
local new_session_id=$(echo "$fork_output" | grep -oP 'A new forked session was created: \Kses_\w+' | tail -1) local after_sessions=$(opencode session list 2>/dev/null | grep -oP '^ses_\w+' | sort)
local new_session_id=""
if [ -z "$new_session_id" ]; then while IFS= read -r sess; do
new_session_id=$(opencode session list 2>/dev/null | grep -E '^ses_' | awk '{print $1}' | grep -v "^$base_session_id$" | head -1) if [[ ! "$before_set" =~ \|${sess}\| ]] && [[ "$sess" != "$base_session_id" ]]; then
new_session_id="$sess"
break
fi fi
done <<< "$after_sessions"
if [ -z "$new_session_id" ]; then if [ -z "$new_session_id" ]; then
echo "Error: Could not find newly created session" >&2 echo "Error: Could not find newly created session" >&2
printf '{"type": "forked", "issue_ref": "%s", "opencode_session_id": "failed", "created_at": "%s", "state": "failed"}\n' \
"$issue_ref" "$(date -Iseconds)" > "$SESSIONS_DIR/$session_file"
exit 1 exit 1
fi fi
printf '{"type": "forked", "issue_ref": "%s", "opencode_session_id": "%s", "created_at": "%s", "state": "idle"}\n' \ printf '{"type": "forked", "issue_ref": "%s", "opencode_session_id": "%s", "created_at": "%s", "state": "idle"}\n' \
"$issue_ref" "$new_session_id" "$(date -Iseconds)" > "$SESSIONS_DIR/$session_file" "$issue_ref" "$new_session_id" "$(date -Iseconds)" > "$SESSIONS_DIR/$session_file"
add_issue_to_index "$issue_ref" "$session_file"
echo "Session started for '$issue_ref': $new_session_id" echo "Session started for '$issue_ref': $new_session_id"
} }