feat(desktop): add consent-aware repository discovery
This commit is contained in:
@@ -65,6 +65,7 @@ When a task changes composition, navigation, overlays, touch behavior, scrolling
|
||||
- Reuse domain hooks, state, view-model derivation, filtering/selection, and action handlers across viewports; keep responsive wrappers focused on presentation. Branch composition when the desktop interaction model depends on width or a fine pointer. Do not mount a heavyweight desktop workbench and merely hide or squeeze it on phones.
|
||||
- Use `useResponsiveBreakpoint` and existing `@kandev/ui` or mobile primitives. Reuse current Dropdown/ContextMenu primitives for contextual actions; use `Drawer` or an existing picker shell for structured phone navigation and choices. Use `useTouchDrawer` when a hover disclosure needs a coarse-pointer alternative.
|
||||
- Keep coarse-pointer and mobile touch targets large enough for touch use, generally at least 44px in the active dimension. This is an active hit-area rule, not a universal desktop visual-size rule: fine-pointer desktop controls should retain the surrounding design-system density, and touch-sized classes such as `h-11` must not become the shared desktop button size.
|
||||
- When one component serves both pointer modes, keep its fine-pointer size as the base class and add the 44px size only behind a coarse-pointer or phone variant. An unqualified `h-11` or `min-h-11` on a desktop-visible shared action is a sizing bug.
|
||||
- Use dynamic viewport units and an explicit internal scroll region for viewport-bound/full-height or potentially overflowing surfaces. Ensure bottom-fixed controls and tall drawers clear safe-area insets; short drawers can retain the shared primitive's intrinsic sizing. Keep document-level horizontal overflow at zero.
|
||||
- If mobile substitutes an unsupported desktop view, derive an effective mobile view without overwriting the user's saved desktop preference.
|
||||
- Use semantic controls, visible labels or accessible names, focus return, and existing design-system components.
|
||||
|
||||
@@ -41,3 +41,15 @@ func (c *Client) SetWorkspacePollMode(ctx context.Context, mode string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RefreshWorkspace requests one file and Git scan from agentctl. The
|
||||
// turn_complete trigger is used by lifecycle completion; manual_refresh is
|
||||
// the default explicit retry from a visible workspace surface.
|
||||
func (c *Client) RefreshWorkspace(ctx context.Context, trigger string) error {
|
||||
if trigger == "" {
|
||||
trigger = "manual_refresh"
|
||||
}
|
||||
return c.updateWorkspace(ctx, "/api/v1/workspace/refresh", "refresh", struct {
|
||||
Trigger string `json:"trigger"`
|
||||
}{Trigger: trigger})
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ func TestSetWorkspacePollMode_PostsExpectedPayload(t *testing.T) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"mode":"slow"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
c := newHTTPOnlyClient(srv.URL)
|
||||
|
||||
@@ -65,12 +65,45 @@ func TestSetWorkspacePollMode_PostsExpectedPayload(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshWorkspace_PostsExpectedTrigger(t *testing.T) {
|
||||
var got struct {
|
||||
Path string
|
||||
Method string
|
||||
Trigger string
|
||||
}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got.Path = r.URL.Path
|
||||
got.Method = r.Method
|
||||
var body struct {
|
||||
Trigger string `json:"trigger"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
got.Trigger = body.Trigger
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
c := newHTTPOnlyClient(srv.URL)
|
||||
if err := c.RefreshWorkspace(context.Background(), "turn_complete"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got.Path != "/api/v1/workspace/refresh" {
|
||||
t.Errorf("path = %q, want /api/v1/workspace/refresh", got.Path)
|
||||
}
|
||||
if got.Method != http.MethodPost {
|
||||
t.Errorf("method = %q, want POST", got.Method)
|
||||
}
|
||||
if got.Trigger != "turn_complete" {
|
||||
t.Errorf("trigger = %q, want turn_complete", got.Trigger)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetWorkspacePollMode_ReturnsErrorOnNon2xx(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"bad mode"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
c := newHTTPOnlyClient(srv.URL)
|
||||
|
||||
@@ -89,7 +122,7 @@ func TestSetWorkspacePollMode_HonoursContextCancellation(t *testing.T) {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
c := newHTTPOnlyClient(srv.URL)
|
||||
|
||||
|
||||
@@ -351,7 +351,7 @@ func (m *Manager) handleCompleteEvent(execution *AgentExecution, event *agentctl
|
||||
evidence := execution.promptAttemptEvidenceSnapshot()
|
||||
failureEvidence = &evidence
|
||||
}
|
||||
m.releaseActivity(executionActivityKey(execution.ID))
|
||||
m.finishExecutionWorkspaceActivity(execution, "turn_complete")
|
||||
|
||||
execution.markAgentActivity()
|
||||
|
||||
|
||||
@@ -111,9 +111,13 @@ func (m *Manager) PromptAgentWithDispatchCallback(ctx context.Context, execution
|
||||
}
|
||||
key := executionActivityKey(executionID)
|
||||
m.trackActivity(key, lease)
|
||||
m.setRuntimeInterest(execution.SessionID, true)
|
||||
result, err := m.sessionManager.SendPromptWithDispatchCallback(ctx, execution, prompt, true, attachments, dispatchOnly, onDispatched)
|
||||
if err != nil || !dispatchOnly {
|
||||
m.releaseActivity(key)
|
||||
if err != nil {
|
||||
m.setRuntimeInterest(execution.SessionID, false)
|
||||
}
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
@@ -133,9 +137,13 @@ func (m *Manager) SteerAgentWithDispatchCallback(ctx context.Context, executionI
|
||||
}
|
||||
key := executionActivityKey(executionID)
|
||||
m.trackActivity(key, lease)
|
||||
m.setRuntimeInterest(execution.SessionID, true)
|
||||
result, err := m.sessionManager.SendPromptSteerWithDispatchCallback(ctx, execution, prompt, true, attachments, dispatchOnly, onDispatched)
|
||||
if err != nil || !dispatchOnly {
|
||||
m.releaseActivity(key)
|
||||
if err != nil {
|
||||
m.setRuntimeInterest(execution.SessionID, false)
|
||||
}
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
@@ -1763,8 +1771,15 @@ func (m *Manager) MarkReady(executionID string) error {
|
||||
//
|
||||
// Publishes events.AgentBootReady. Returns error if execution not found.
|
||||
func (m *Manager) MarkBootReady(executionID string) error {
|
||||
execution, exists := m.executionStore.Get(executionID)
|
||||
if exists {
|
||||
m.finalWorkspaceRefresh(execution, "startup_grace")
|
||||
}
|
||||
err := m.markReadyEventWithContext(context.Background(), executionID, events.AgentBootReady, false)
|
||||
if err == nil {
|
||||
if exists {
|
||||
m.setRuntimeInterest(execution.SessionID, false)
|
||||
}
|
||||
m.releaseActivity(executionActivityKey(executionID))
|
||||
}
|
||||
return err
|
||||
|
||||
@@ -312,7 +312,6 @@ func (m *Manager) cleanupStaleExecution(ctx context.Context, execution *AgentExe
|
||||
execution.remoteInstanceLifecycleMu.Lock()
|
||||
defer execution.remoteInstanceLifecycleMu.Unlock()
|
||||
execution.agentctlLifecycleMu.Lock()
|
||||
defer execution.agentctlLifecycleMu.Unlock()
|
||||
sessionID := execution.SessionID
|
||||
|
||||
m.logger.Info("cleaning up stale agent execution",
|
||||
@@ -324,6 +323,7 @@ func (m *Manager) cleanupStaleExecution(ctx context.Context, execution *AgentExe
|
||||
// execution is created for the same session, causing git polling on deleted worktrees.
|
||||
// This is idempotent — returns success if the instance is already gone.
|
||||
if err := m.stopAgentViaBackend(ctx, execution.ID, execution, stopReasonStaleExecutionCleanup, false, false); err != nil {
|
||||
execution.agentctlLifecycleMu.Unlock()
|
||||
return fmt.Errorf("stop stale runtime %s: %w", execution.ID, err)
|
||||
}
|
||||
|
||||
@@ -335,6 +335,8 @@ func (m *Manager) cleanupStaleExecution(ctx context.Context, execution *AgentExe
|
||||
if client := execution.currentAgentCtlClient(); client != nil { // protected by agentctlLifecycleMu
|
||||
client.Close()
|
||||
}
|
||||
execution.detachAgentctlClient()
|
||||
execution.agentctlLifecycleMu.Unlock()
|
||||
|
||||
// Remove from execution store
|
||||
m.RemoveExecution(execution.ID)
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -213,6 +214,58 @@ func TestManager_CleanupStaleExecution_SkipsStopWhenNoRuntime(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_CleanupStaleExecution_ReleasesAgentctlLockBeforeRemove(t *testing.T) {
|
||||
mgr := newTestManager(t)
|
||||
modes := make(chan string, 1)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/v1/workspace/poll-mode" {
|
||||
modes <- r.Method
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
port := srv.Listener.Addr().(*net.TCPAddr).Port
|
||||
client := agentctl.NewClient("127.0.0.1", port, newTestLogger())
|
||||
t.Cleanup(func() { client.Close() })
|
||||
execution := &AgentExecution{
|
||||
ID: "exec-with-poll-client",
|
||||
SessionID: "session-with-poll-client",
|
||||
WorkspacePath: "/tmp/workspace-with-poll-client",
|
||||
agentctl: client,
|
||||
}
|
||||
if err := mgr.executionStore.Add(execution); err != nil {
|
||||
t.Fatalf("add execution: %v", err)
|
||||
}
|
||||
|
||||
// Runtime interest makes RemoveExecution publish the transition to paused.
|
||||
// The cleanup path must detach the client before that transition attempts to
|
||||
// acquire the client read lock.
|
||||
mgr.pollAggregator.HandleRuntimeInterest(execution.SessionID, true)
|
||||
select {
|
||||
case <-modes:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for initial poll-mode push")
|
||||
}
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- mgr.CleanupStaleExecutionBySessionID(context.Background(), execution.SessionID)
|
||||
}()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("cleanup stale execution: %v", err)
|
||||
}
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
t.Fatal("cleanup stale execution blocked while removing execution")
|
||||
}
|
||||
|
||||
if _, found := mgr.GetExecutionBySessionID(execution.SessionID); found {
|
||||
t.Fatal("expected stale execution to be removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_CleanupStaleExecution_PreservesTrackingOnStopError(t *testing.T) {
|
||||
log := newTestRegistryLogger()
|
||||
reg := newTestRegistry()
|
||||
|
||||
@@ -74,6 +74,9 @@ type workspacePollAggregator struct {
|
||||
// Last-write-wins queue: pendingPush + pushInFlight serialize per-workspace HTTP pushes so order matches enqueue.
|
||||
pendingPush map[string]workspacePushTarget
|
||||
pushInFlight map[string]bool
|
||||
// dirtyPush records a desired mode whose last RPC failed. The next
|
||||
// contribution event retries it even when the effective mode is unchanged.
|
||||
dirtyPush map[string]bool
|
||||
}
|
||||
|
||||
// workspacePushTarget bundles the queued mode and execution resolved at enqueue time.
|
||||
@@ -95,6 +98,7 @@ func newWorkspacePollAggregator(mgr *Manager) *workspacePollAggregator {
|
||||
runtimeWorkspaceBySession: make(map[string]string),
|
||||
pendingPush: make(map[string]workspacePushTarget),
|
||||
pushInFlight: make(map[string]bool),
|
||||
dirtyPush: make(map[string]bool),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,16 +244,18 @@ func (a *workspacePollAggregator) effectiveModeLocked(workspacePath string) Work
|
||||
// to retry a mode that may have been sent before agentctl accepted requests.
|
||||
func (a *workspacePollAggregator) applyEffectiveModeLocked(workspacePath string, effective WorkspacePollMode, force bool) bool {
|
||||
prev, hadPrev := a.lastPushed[workspacePath]
|
||||
shouldPush := force || !hadPrev || prev != effective
|
||||
if !force && !hadPrev && effective == WorkspacePollModePaused {
|
||||
shouldPush := force || a.dirtyPush[workspacePath] || !hadPrev || prev != effective
|
||||
if !force && !hadPrev && effective == WorkspacePollModePaused && !a.dirtyPush[workspacePath] {
|
||||
return false
|
||||
}
|
||||
if effective == WorkspacePollModePaused {
|
||||
delete(a.lastPushed, workspacePath)
|
||||
} else {
|
||||
a.lastPushed[workspacePath] = effective
|
||||
// Keep the mode map bounded, but still report a transition from an
|
||||
// already-managed mode so pushAsync delivers the paused state.
|
||||
return shouldPush
|
||||
}
|
||||
return shouldPush && effective != WorkspacePollModePaused
|
||||
a.lastPushed[workspacePath] = effective
|
||||
return shouldPush
|
||||
}
|
||||
|
||||
// recordAndCompute updates the per-session mode for the given workspace and
|
||||
@@ -325,11 +331,18 @@ func (a *workspacePollAggregator) pushLoop(workspacePath string) {
|
||||
cancel()
|
||||
releaseClient()
|
||||
if err != nil {
|
||||
a.mu.Lock()
|
||||
a.dirtyPush[workspacePath] = true
|
||||
a.mu.Unlock()
|
||||
a.mgr.logger.Warn("failed to push workspace poll mode",
|
||||
zap.String("workspace", workspacePath),
|
||||
zap.String("mode", string(target.mode)),
|
||||
zap.Error(err))
|
||||
continue
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.dirtyPush, workspacePath)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package lifecycle
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
@@ -203,6 +204,128 @@ func TestAggregator_RuntimeInterestRemovalYieldsPaused(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAggregator_RuntimeInterestRemovalDeliversPaused(t *testing.T) {
|
||||
modes := make(chan string, 4)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/workspace/poll-mode" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
modes <- body.Mode
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
mgr := newTestManagerForAggregator(t)
|
||||
port := srv.Listener.Addr().(*net.TCPAddr).Port
|
||||
client := agentctl.NewClient("127.0.0.1", port, newTestLogger())
|
||||
t.Cleanup(func() { client.Close() })
|
||||
execution := &AgentExecution{
|
||||
ID: "exec-s1", SessionID: "s1", WorkspacePath: "/tmp/ws1", agentctl: client,
|
||||
}
|
||||
if err := mgr.executionStore.Add(execution); err != nil {
|
||||
t.Fatalf("add execution: %v", err)
|
||||
}
|
||||
|
||||
mgr.pollAggregator.HandleRuntimeInterest("s1", true)
|
||||
select {
|
||||
case got := <-modes:
|
||||
if got != string(WorkspacePollModeSlow) {
|
||||
t.Fatalf("initial runtime mode = %q, want slow", got)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for runtime poll mode")
|
||||
}
|
||||
|
||||
mgr.pollAggregator.HandleRuntimeInterest("s1", false)
|
||||
select {
|
||||
case got := <-modes:
|
||||
if got != string(WorkspacePollModePaused) {
|
||||
t.Fatalf("final runtime mode = %q, want paused", got)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for paused poll mode")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAggregator_FailedPausedPushIsRetriedOnUnchangedContribution(t *testing.T) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
pausedCalls int
|
||||
modes = make(chan string, 4)
|
||||
)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
modes <- body.Mode
|
||||
if body.Mode == string(WorkspacePollModePaused) {
|
||||
mu.Lock()
|
||||
pausedCalls++
|
||||
call := pausedCalls
|
||||
mu.Unlock()
|
||||
if call == 1 {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
mgr := newTestManagerForAggregator(t)
|
||||
addExecutionWithClient(t, mgr, "s1", "/tmp/ws1", srv.URL)
|
||||
|
||||
mgr.pollAggregator.HandleRuntimeInterest("s1", true)
|
||||
if got := <-modes; got != string(WorkspacePollModeSlow) {
|
||||
t.Fatalf("initial runtime mode = %q, want slow", got)
|
||||
}
|
||||
mgr.pollAggregator.HandleRuntimeInterest("s1", false)
|
||||
if got := <-modes; got != string(WorkspacePollModePaused) {
|
||||
t.Fatalf("first paused mode = %q, want paused", got)
|
||||
}
|
||||
|
||||
// The first paused RPC failed. A repeated paused contribution must not be
|
||||
// suppressed just because the desired mode was already recorded locally.
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
mgr.pollAggregator.mu.Lock()
|
||||
dirty := mgr.pollAggregator.dirtyPush["/tmp/ws1"]
|
||||
mgr.pollAggregator.mu.Unlock()
|
||||
if dirty {
|
||||
break
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
mgr.pollAggregator.mu.Lock()
|
||||
dirty := mgr.pollAggregator.dirtyPush["/tmp/ws1"]
|
||||
mgr.pollAggregator.mu.Unlock()
|
||||
if !dirty {
|
||||
t.Fatal("first paused RPC did not record a dirty retry state")
|
||||
}
|
||||
mgr.pollAggregator.HandleRuntimeInterest("s1", false)
|
||||
if got := <-modes; got != string(WorkspacePollModePaused) {
|
||||
t.Fatalf("retried paused mode = %q, want paused", got)
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if pausedCalls != 2 {
|
||||
t.Fatalf("paused RPC calls = %d, want 2", pausedCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAggregator_FlushSessionMode_PushesRuntimeBaselineWithoutCachedUIState(t *testing.T) {
|
||||
mgr := newTestManagerForAggregator(t)
|
||||
addExecution(mgr, "s1", "/tmp/ws1")
|
||||
@@ -412,7 +535,7 @@ func TestAggregator_PushAsync_LastWriteWinsUnderRace(t *testing.T) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
mgr := newTestManagerForAggregator(t)
|
||||
addExecutionWithClient(t, mgr, "s1", "/tmp/ws1", srv.URL)
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// finalWorkspaceRefreshTimeout bounds the synchronous scan at a turn
|
||||
// boundary. It is a variable so lifecycle tests can keep the boundary short.
|
||||
var finalWorkspaceRefreshTimeout = 10 * time.Second
|
||||
|
||||
// finalWorkspaceRefresh completes the workspace side of a turn before the
|
||||
// lifecycle manager releases runtime interest. That ordering leaves the
|
||||
// cached Git/file state current when the tracker transitions to idle polling.
|
||||
func (m *Manager) finalWorkspaceRefresh(execution *AgentExecution, trigger string) {
|
||||
if execution == nil {
|
||||
return
|
||||
}
|
||||
client, releaseClient := execution.AcquireAgentCtlClient()
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
defer releaseClient()
|
||||
timeout := finalWorkspaceRefreshTimeout
|
||||
if timeout <= 0 {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
if err := client.RefreshWorkspace(ctx, trigger); err != nil && m.logger != nil {
|
||||
m.logger.Warn("final workspace refresh failed",
|
||||
zap.String("operation", "workspace.final_refresh"),
|
||||
zap.String("trigger", trigger),
|
||||
zap.String("execution_id", execution.ID),
|
||||
zap.String("task_id", execution.TaskID),
|
||||
zap.String("session_id", execution.SessionID),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) finishExecutionWorkspaceActivity(execution *AgentExecution, trigger string) {
|
||||
if execution == nil {
|
||||
return
|
||||
}
|
||||
m.finalWorkspaceRefresh(execution, trigger)
|
||||
m.releaseActivity(executionActivityKey(execution.ID))
|
||||
m.setRuntimeInterest(execution.SessionID, false)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
agentctl "github.com/kandev/kandev/internal/agent/runtime/agentctl"
|
||||
)
|
||||
|
||||
func TestFinishExecutionWorkspaceActivityRefreshesBeforePausingRuntime(t *testing.T) {
|
||||
events := make(chan string, 4)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/workspace/poll-mode":
|
||||
var body struct {
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
events <- r.URL.Path + ":" + body.Mode
|
||||
case "/api/v1/workspace/refresh":
|
||||
events <- r.URL.Path
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
mgr := newTestManagerForAggregator(t)
|
||||
port := srv.Listener.Addr().(*net.TCPAddr).Port
|
||||
client := agentctl.NewClient("127.0.0.1", port, newTestLogger())
|
||||
t.Cleanup(func() { client.Close() })
|
||||
execution := &AgentExecution{
|
||||
ID: "exec-s1", SessionID: "s1", TaskID: "task-1", WorkspacePath: "/tmp/ws1", agentctl: client,
|
||||
}
|
||||
if err := mgr.executionStore.Add(execution); err != nil {
|
||||
t.Fatalf("add execution: %v", err)
|
||||
}
|
||||
|
||||
mgr.setRuntimeInterest("s1", true)
|
||||
select {
|
||||
case got := <-events:
|
||||
if got != "/api/v1/workspace/poll-mode:slow" {
|
||||
t.Fatalf("initial runtime event = %q, want slow poll mode", got)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for initial runtime poll mode")
|
||||
}
|
||||
|
||||
mgr.finishExecutionWorkspaceActivity(execution, "turn_complete")
|
||||
first := eventsWithTimeout(t, events)
|
||||
second := eventsWithTimeout(t, events)
|
||||
if first != "/api/v1/workspace/refresh" {
|
||||
t.Fatalf("first completion event = %q, want final refresh", first)
|
||||
}
|
||||
if second != "/api/v1/workspace/poll-mode:paused" {
|
||||
t.Fatalf("second completion event = %q, want paused poll mode", second)
|
||||
}
|
||||
}
|
||||
|
||||
func eventsWithTimeout(t *testing.T, events <-chan string) string {
|
||||
t.Helper()
|
||||
timer := time.NewTimer(2 * time.Second)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case event := <-events:
|
||||
return event
|
||||
case <-timer.C:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
@@ -116,6 +116,7 @@ func (s *Server) setupRoutes() {
|
||||
|
||||
// Workspace state (poll mode driven by gateway focus signal)
|
||||
api.POST("/workspace/poll-mode", s.handleSetPollMode)
|
||||
api.POST("/workspace/refresh", s.handleRefreshWorkspace)
|
||||
|
||||
// Workspace rescan: triggered by the kandev backend after a new
|
||||
// sibling worktree appears on disk (multi-branch add_branch flow).
|
||||
|
||||
@@ -13,6 +13,11 @@ type SetPollModeRequest struct {
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
|
||||
// RefreshWorkspaceRequest is the body for POST /api/v1/workspace/refresh.
|
||||
type RefreshWorkspaceRequest struct {
|
||||
Trigger string `json:"trigger,omitempty"`
|
||||
}
|
||||
|
||||
// handleSetPollMode updates the workspace tracker's poll mode based on the
|
||||
// gateway's view of UI subscription/focus state for sessions in this workspace.
|
||||
//
|
||||
@@ -50,3 +55,20 @@ func (s *Server) handleSetPollMode(c *gin.Context) {
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"mode": req.Mode})
|
||||
}
|
||||
|
||||
// handleRefreshWorkspace performs one explicit file and Git scan. Lifecycle
|
||||
// callers use the turn_complete trigger; browser callers use the default
|
||||
// manual_refresh trigger, which also retries a tracker paused by denial.
|
||||
func (s *Server) handleRefreshWorkspace(c *gin.Context) {
|
||||
var req RefreshWorkspaceRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request: " + err.Error()})
|
||||
return
|
||||
}
|
||||
trigger := req.Trigger
|
||||
if trigger == "" {
|
||||
trigger = "manual_refresh"
|
||||
}
|
||||
s.procMgr.RefreshWorkspace(c.Request.Context(), trigger)
|
||||
c.JSON(http.StatusOK, gin.H{"trigger": process.NormalizeWorkspaceTrigger(trigger)})
|
||||
}
|
||||
|
||||
@@ -84,3 +84,52 @@ func TestHandleSetPollMode_EmptyMode(t *testing.T) {
|
||||
t.Errorf("expected 400 for empty mode, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleRefreshWorkspace_AcceptsTrigger(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
trigger string
|
||||
want string
|
||||
}{
|
||||
{name: "explicit", trigger: "turn_complete", want: "turn_complete"},
|
||||
{name: "empty", trigger: "", want: "manual_refresh"},
|
||||
{name: "unsupported", trigger: "background_poll", want: "manual_refresh"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := newTestServer(t)
|
||||
body, _ := json.Marshal(RefreshWorkspaceRequest{Trigger: tc.trigger})
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/workspace/refresh", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
s.router.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d (body: %s)", w.Code, w.Body.String())
|
||||
}
|
||||
var response struct {
|
||||
Trigger string `json:"trigger"`
|
||||
}
|
||||
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if response.Trigger != tc.want {
|
||||
t.Fatalf("response trigger = %q, want %q", response.Trigger, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleRefreshWorkspace_RejectsInvalidBody(t *testing.T) {
|
||||
s := newTestServer(t)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/workspace/refresh", bytes.NewReader([]byte(`not json`)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
s.router.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400 for invalid body, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,9 @@ var ambientEnvNotScrubbed = []string{
|
||||
// files are parsed by the guard below regardless of build tags (only one
|
||||
// compiles per platform), so both names must stay exempt.
|
||||
"COMSPEC",
|
||||
// KANDEV_DESKTOP_RUNTIME describes the launch policy inherited by the
|
||||
// agentctl child. Keep it intact so diagnostics reflect the real runtime.
|
||||
"KANDEV_DESKTOP_RUNTIME",
|
||||
}
|
||||
|
||||
// clearAmbientGitLabEnv removes the inherited GitLab host/token values so
|
||||
|
||||
@@ -1009,6 +1009,20 @@ func (m *Manager) SetWorkspacePollMode(ctx context.Context, mode PollMode) {
|
||||
}()
|
||||
}
|
||||
|
||||
// RefreshWorkspace performs one file and Git scan across the root and all
|
||||
// repository trackers. Lifecycle uses this at turn completion; the manual
|
||||
// refresh surface uses it as an explicit access retry.
|
||||
func (m *Manager) RefreshWorkspace(ctx context.Context, trigger string) {
|
||||
trigger = NormalizeWorkspaceTrigger(trigger)
|
||||
root, trackers := m.snapshotTrackers()
|
||||
if root != nil {
|
||||
root.RefreshWorkspace(ctx, trigger)
|
||||
}
|
||||
for _, tracker := range trackers {
|
||||
tracker.RefreshWorkspace(ctx, trigger)
|
||||
}
|
||||
}
|
||||
|
||||
// GitOperator returns the git operator for git operations against the
|
||||
// workspace root. Lazy-initialized.
|
||||
func (m *Manager) GitOperator() *GitOperator {
|
||||
|
||||
@@ -78,6 +78,9 @@ func (m *Manager) buildWorkspaceTrackerGraph(
|
||||
}
|
||||
|
||||
func (m *Manager) configureTracker(tracker *WorkspaceTracker, repositoryName string, roots []string) {
|
||||
if m.cfg != nil {
|
||||
tracker.SetDiagnosticIdentity(m.cfg.TaskID, m.cfg.SessionID)
|
||||
}
|
||||
tracker.SetGitEnvironment(m.trackerGitEnvironment())
|
||||
tracker.SetAllowedSourceRoots(roots)
|
||||
if !tracker.IsSubmodule() {
|
||||
|
||||
@@ -23,6 +23,45 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestManagerRefreshWorkspaceNormalizesTriggerForEveryTracker(t *testing.T) {
|
||||
log := newTestLogger(t)
|
||||
rootDir, cleanupRoot := setupTestRepo(t)
|
||||
t.Cleanup(cleanupRoot)
|
||||
repoDir, cleanupRepo := setupTestRepo(t)
|
||||
t.Cleanup(cleanupRepo)
|
||||
thirdDir, cleanupThird := setupTestRepo(t)
|
||||
t.Cleanup(cleanupThird)
|
||||
|
||||
root := NewWorkspaceTracker(rootDir, log)
|
||||
firstRepo := NewWorkspaceTrackerForRepo(repoDir, "first", log)
|
||||
secondRepo := NewWorkspaceTrackerForRepo(thirdDir, "second", log)
|
||||
t.Cleanup(root.Stop)
|
||||
t.Cleanup(firstRepo.Stop)
|
||||
t.Cleanup(secondRepo.Stop)
|
||||
|
||||
trackers := []*WorkspaceTracker{root, firstRepo, secondRepo}
|
||||
for _, tracker := range trackers {
|
||||
tracker.SetPollMode(PollModePaused)
|
||||
tracker.accessDenied.Store(true)
|
||||
}
|
||||
|
||||
mgr := &Manager{
|
||||
logger: log,
|
||||
workspaceTracker: root,
|
||||
repoTrackers: []*WorkspaceTracker{firstRepo, secondRepo},
|
||||
}
|
||||
mgr.RefreshWorkspace(context.Background(), "unsupported_trigger")
|
||||
|
||||
for i, tracker := range trackers {
|
||||
if got := tracker.GetPollMode(); got != PollModeFast {
|
||||
t.Errorf("tracker %d poll mode = %q, want fast", i, got)
|
||||
}
|
||||
if tracker.accessDenied.Load() {
|
||||
t.Errorf("tracker %d retained access denial after manual refresh", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishMCPAttachmentPublishesWithoutBlocking(t *testing.T) {
|
||||
m := &Manager{
|
||||
updatesCh: make(chan adapter.AgentEvent, 1),
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/kandev/kandev/internal/common/fsdiagnostics"
|
||||
)
|
||||
|
||||
type workspaceTriggerContextKey struct{}
|
||||
|
||||
const (
|
||||
workspaceManualRefreshTrigger = "manual_refresh"
|
||||
workspaceUserSelectTrigger = "user_select"
|
||||
)
|
||||
|
||||
// NormalizeWorkspaceTrigger keeps refresh diagnostics within the set of
|
||||
// lifecycle and user-operation causes understood by the tracker.
|
||||
func NormalizeWorkspaceTrigger(trigger string) string {
|
||||
switch trigger {
|
||||
case workspaceManualRefreshTrigger, workspaceUserSelectTrigger, "turn_complete", "startup_grace":
|
||||
return trigger
|
||||
default:
|
||||
return workspaceManualRefreshTrigger
|
||||
}
|
||||
}
|
||||
|
||||
func withWorkspaceTrigger(ctx context.Context, trigger string) context.Context {
|
||||
return context.WithValue(ctx, workspaceTriggerContextKey{}, trigger)
|
||||
}
|
||||
|
||||
func workspaceTrigger(ctx context.Context, fallback string) string {
|
||||
if trigger, ok := ctx.Value(workspaceTriggerContextKey{}).(string); ok && trigger != "" {
|
||||
return trigger
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
// SetDiagnosticIdentity supplies the task and session that own this tracker.
|
||||
// The workspace path remains the canonical operation target because agentctl
|
||||
// instances do not receive a separate workspace UUID.
|
||||
func (wt *WorkspaceTracker) SetDiagnosticIdentity(taskID, sessionID string) {
|
||||
wt.diagnosticMu.Lock()
|
||||
wt.diagnosticTaskID = taskID
|
||||
wt.diagnosticSessionID = sessionID
|
||||
wt.diagnosticMu.Unlock()
|
||||
}
|
||||
|
||||
func (wt *WorkspaceTracker) diagnosticContext(operation, trigger string) fsdiagnostics.Context {
|
||||
wt.diagnosticMu.RLock()
|
||||
taskID := wt.diagnosticTaskID
|
||||
sessionID := wt.diagnosticSessionID
|
||||
wt.diagnosticMu.RUnlock()
|
||||
return fsdiagnostics.Context{
|
||||
Operation: operation,
|
||||
Target: wt.workDir,
|
||||
Trigger: trigger,
|
||||
Runtime: wt.runtimeMode,
|
||||
TaskID: taskID,
|
||||
SessionID: sessionID,
|
||||
PollMode: string(wt.GetPollMode()),
|
||||
}
|
||||
}
|
||||
|
||||
func (wt *WorkspaceTracker) recordFilesystemFailure(operation, trigger string, err error) {
|
||||
if wt.logger == nil || err == nil {
|
||||
return
|
||||
}
|
||||
operationContext := wt.diagnosticContext(operation, trigger)
|
||||
if fsdiagnostics.IsAccessDenied(err) {
|
||||
wt.filesystemWarnings.Warn(wt.logger.Zap(), "filesystem.access_denied", operationContext, err)
|
||||
wt.pauseAfterAccessDenied(operationContext, err)
|
||||
return
|
||||
}
|
||||
wt.logger.Warn("filesystem operation failed", operationContext.Fields(err)...)
|
||||
}
|
||||
|
||||
func (wt *WorkspaceTracker) pauseAfterAccessDenied(operationContext fsdiagnostics.Context, err error) {
|
||||
if !wt.accessDenied.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
wt.pollModeMu.Lock()
|
||||
previous := wt.pollMode
|
||||
wt.pollMode = PollModePaused
|
||||
wt.pollModeMu.Unlock()
|
||||
if previous != PollModePaused {
|
||||
wt.wakePollLoops()
|
||||
}
|
||||
wt.logger.Warn("workspace.poll_paused_after_denial", operationContext.Fields(err)...)
|
||||
}
|
||||
|
||||
func (wt *WorkspaceTracker) clearAccessDeniedForUserOperation(trigger string) {
|
||||
if trigger == workspaceManualRefreshTrigger || trigger == workspaceUserSelectTrigger {
|
||||
wt.accessDenied.Store(false)
|
||||
}
|
||||
}
|
||||
@@ -1,149 +1,59 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/agentctl/server/config"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"go.uber.org/zap/zaptest/observer"
|
||||
)
|
||||
|
||||
// TestWorkspaceTracker_GitPollTickStats_AccumulatesAcrossTicks pins the
|
||||
// accumulation contract behind the diagnostic agentctl_git_poll_ms metric:
|
||||
// GitPollTickStats must report zero before any tick has completed, and must
|
||||
// report a growing count with a non-zero total after ticks run, regardless
|
||||
// of whether individual ticks succeed.
|
||||
func TestWorkspaceTracker_GitPollTickStats_AccumulatesAcrossTicks(t *testing.T) {
|
||||
repoDir, cleanup := setupTestRepo(t)
|
||||
t.Cleanup(cleanup)
|
||||
func TestWorkspaceTrackerAccessDeniedPausesUntilVisibleRetry(t *testing.T) {
|
||||
wt := newGraceTestTracker(t, graceNeverFires)
|
||||
core, logs := observer.New(zapcore.WarnLevel)
|
||||
log, err := logger.NewFromZap(zap.New(core))
|
||||
if err != nil {
|
||||
t.Fatalf("NewFromZap: %v", err)
|
||||
}
|
||||
wt.logger = log
|
||||
wt.SetDiagnosticIdentity("task-1", "session-1")
|
||||
|
||||
log := newTestLogger(t)
|
||||
wt := NewWorkspaceTracker(repoDir, log)
|
||||
ctx := context.Background()
|
||||
|
||||
if count, total := wt.GitPollTickStats(); count != 0 || total != 0 {
|
||||
t.Fatalf("GitPollTickStats before any tick = (%d, %d), want (0, 0)", count, total)
|
||||
denied := errors.New("permission denied")
|
||||
for range 3 {
|
||||
wt.recordFilesystemFailure("workspace.git_poll", "poll", denied)
|
||||
}
|
||||
if got := wt.GetPollMode(); got != PollModePaused {
|
||||
t.Fatalf("poll mode after denial = %v, want paused", got)
|
||||
}
|
||||
if !wt.accessDenied.Load() {
|
||||
t.Fatal("access denial was not retained")
|
||||
}
|
||||
if got := logs.Len(); got != 2 {
|
||||
t.Fatalf("warning count after repeated denial = %d, want initial denial and pause", got)
|
||||
}
|
||||
|
||||
var consecutiveFailures int
|
||||
if stop := wt.gitPollTick(ctx, &consecutiveFailures); stop {
|
||||
t.Fatal("gitPollTick unexpectedly signalled stop")
|
||||
wt.SetPollMode(PollModeSlow)
|
||||
if got := wt.GetPollMode(); got != PollModePaused {
|
||||
t.Fatalf("poll mode after slow background update = %v, want paused", got)
|
||||
}
|
||||
|
||||
firstCount, firstTotal := wt.GitPollTickStats()
|
||||
if firstCount != 1 {
|
||||
t.Fatalf("count after one tick = %d, want 1", firstCount)
|
||||
wt.SetPollMode(PollModeFast)
|
||||
if got := wt.GetPollMode(); got != PollModeFast {
|
||||
t.Fatalf("poll mode after focused retry = %v, want fast", got)
|
||||
}
|
||||
if firstTotal <= 0 {
|
||||
t.Fatalf("totalNanos after one tick = %d, want > 0", firstTotal)
|
||||
}
|
||||
|
||||
if stop := wt.gitPollTick(ctx, &consecutiveFailures); stop {
|
||||
t.Fatal("gitPollTick unexpectedly signalled stop")
|
||||
}
|
||||
|
||||
secondCount, secondTotal := wt.GitPollTickStats()
|
||||
if secondCount != 2 {
|
||||
t.Fatalf("count after two ticks = %d, want 2", secondCount)
|
||||
}
|
||||
if secondTotal <= firstTotal {
|
||||
t.Fatalf("totalNanos after two ticks = %d, want > %d", secondTotal, firstTotal)
|
||||
if wt.accessDenied.Load() {
|
||||
t.Fatal("focused retry did not clear access denial")
|
||||
}
|
||||
}
|
||||
|
||||
// TestManager_GitPollStats_AggregatesRootTracker exercises the
|
||||
// process.Manager-level aggregator that api.handleSystemMetrics reads. It
|
||||
// must report unavailable (count 0) before any tick, and a plausible mean
|
||||
// once the root tracker has recorded ticks.
|
||||
func TestManager_GitPollStats_AggregatesRootTracker(t *testing.T) {
|
||||
repoDir, cleanup := setupTestRepo(t)
|
||||
t.Cleanup(cleanup)
|
||||
func TestWorkspaceTrackerCapturesRuntimeModeAtConstruction(t *testing.T) {
|
||||
t.Setenv("KANDEV_DESKTOP_RUNTIME", "true")
|
||||
tracker := NewWorkspaceTracker(t.TempDir(), newTestLogger(t))
|
||||
t.Cleanup(tracker.Stop)
|
||||
|
||||
log := newTestLogger(t)
|
||||
cfg := &config.InstanceConfig{WorkDir: repoDir}
|
||||
m := NewManager(cfg, log)
|
||||
|
||||
if count, mean := m.GitPollStats(); count != 0 || mean != 0 {
|
||||
t.Fatalf("GitPollStats before any tick = (%d, %f), want (0, 0)", count, mean)
|
||||
}
|
||||
|
||||
root, _ := m.snapshotTrackers()
|
||||
if root == nil {
|
||||
t.Fatal("expected a root workspace tracker")
|
||||
}
|
||||
var consecutiveFailures int
|
||||
root.gitPollTick(context.Background(), &consecutiveFailures)
|
||||
root.gitPollTick(context.Background(), &consecutiveFailures)
|
||||
|
||||
count, mean := m.GitPollStats()
|
||||
if count != 2 {
|
||||
t.Fatalf("count after two ticks = %d, want 2", count)
|
||||
}
|
||||
if mean <= 0 {
|
||||
t.Fatalf("mean after two ticks = %f, want > 0", mean)
|
||||
}
|
||||
}
|
||||
|
||||
// TestManager_GitPollStats_AggregatesAcrossRepoTrackers exercises the
|
||||
// multi-repo half of GitPollStats: with a second WorkspaceTracker added to
|
||||
// m.repoTrackers (the shape a multi-repo task root produces), the aggregate
|
||||
// count and mean must include both the root tracker's and the extra
|
||||
// tracker's ticks, not just the root's.
|
||||
func TestManager_GitPollStats_AggregatesAcrossRepoTrackers(t *testing.T) {
|
||||
repoDir, cleanup := setupTestRepo(t)
|
||||
t.Cleanup(cleanup)
|
||||
repoDir2, cleanup2 := setupTestRepo(t)
|
||||
t.Cleanup(cleanup2)
|
||||
|
||||
log := newTestLogger(t)
|
||||
cfg := &config.InstanceConfig{WorkDir: repoDir}
|
||||
m := NewManager(cfg, log)
|
||||
|
||||
root, _ := m.snapshotTrackers()
|
||||
if root == nil {
|
||||
t.Fatal("expected a root workspace tracker")
|
||||
}
|
||||
var consecutiveFailures int
|
||||
root.gitPollTick(context.Background(), &consecutiveFailures)
|
||||
root.gitPollTick(context.Background(), &consecutiveFailures)
|
||||
|
||||
extra := NewWorkspaceTrackerForRepo(repoDir2, "extra-repo", log)
|
||||
extra.gitPollTick(context.Background(), &consecutiveFailures)
|
||||
|
||||
m.repoTrackersMu.Lock()
|
||||
m.repoTrackers = append(m.repoTrackers, extra)
|
||||
m.repoTrackersMu.Unlock()
|
||||
|
||||
count, mean := m.GitPollStats()
|
||||
if count != 3 {
|
||||
t.Fatalf("count across root + extra tracker = %d, want 3 (2 from root + 1 from extra)", count)
|
||||
}
|
||||
if mean <= 0 {
|
||||
t.Fatalf("mean across root + extra tracker = %f, want > 0", mean)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_MonitorPollStats_AggregatesWorkspaceMonitorTicks(t *testing.T) {
|
||||
repoDir, cleanup := setupTestRepo(t)
|
||||
t.Cleanup(cleanup)
|
||||
|
||||
log := newTestLogger(t)
|
||||
m := NewManager(&config.InstanceConfig{WorkDir: repoDir}, log)
|
||||
root, _ := m.snapshotTrackers()
|
||||
if root == nil {
|
||||
t.Fatal("expected a root workspace tracker")
|
||||
}
|
||||
|
||||
lastState := workspaceState{}
|
||||
var consecutiveFailures int
|
||||
if stop := root.monitorTick(context.Background(), &lastState, &consecutiveFailures); stop {
|
||||
t.Fatal("monitorTick unexpectedly signalled stop")
|
||||
}
|
||||
|
||||
count, mean := m.MonitorPollStats()
|
||||
if count != 1 {
|
||||
t.Fatalf("MonitorPollStats count = %d, want 1", count)
|
||||
}
|
||||
if mean <= 0 {
|
||||
t.Fatalf("MonitorPollStats mean = %f, want > 0", mean)
|
||||
t.Setenv("KANDEV_DESKTOP_RUNTIME", "false")
|
||||
if got := tracker.diagnosticContext("workspace.file_monitor", "poll").Runtime; got != "desktop" {
|
||||
t.Fatalf("diagnostic runtime = %q, want desktop", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,9 +58,16 @@ func isRootOwnershipMarkerPath(path string) bool {
|
||||
|
||||
// updateFiles updates the file listing
|
||||
func (wt *WorkspaceTracker) updateFiles(ctx context.Context) {
|
||||
files, err := wt.getFileListClass(ctx, subproc.GitBackground)
|
||||
wt.updateFilesClass(ctx, subproc.GitBackground)
|
||||
}
|
||||
|
||||
func (wt *WorkspaceTracker) updateFilesClass(ctx context.Context, class subproc.GitWorkClass) {
|
||||
files, err := wt.getFileListClass(ctx, class)
|
||||
if err != nil {
|
||||
wt.logger.Debug("failed to get file list", zap.Error(err))
|
||||
wt.recordFilesystemFailure("workspace.file_monitor", workspaceTrigger(ctx, "poll"), err)
|
||||
return
|
||||
}
|
||||
if err := ctx.Err(); err != nil || (wt.cancelCtx != nil && wt.cancelCtx.Err() != nil) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -129,6 +136,7 @@ func (wt *WorkspaceTracker) GetFileTree(reqPath string, depth int) (*types.FileT
|
||||
// Check if path exists
|
||||
info, err := os.Stat(safePath)
|
||||
if err != nil {
|
||||
wt.recordFilesystemFailure("workspace.file_tree", "user_select", err)
|
||||
return nil, fmt.Errorf("path not found: %w", err)
|
||||
}
|
||||
|
||||
@@ -158,6 +166,7 @@ func (wt *WorkspaceTracker) buildFileTreeNode(safePath, relPath string, info os.
|
||||
// Read directory contents
|
||||
entries, err := os.ReadDir(safePath)
|
||||
if err != nil {
|
||||
wt.recordFilesystemFailure("workspace.file_tree", "user_select", err)
|
||||
return node, nil // Return node without children on error
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/agentctl/types"
|
||||
"github.com/kandev/kandev/internal/common/fsdiagnostics"
|
||||
"github.com/kandev/kandev/internal/common/subproc"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -141,6 +142,11 @@ func (wt *WorkspaceTracker) gitPollTick(ctx context.Context, consecutiveFailures
|
||||
//
|
||||
// Returns true if pollGitChanges should exit.
|
||||
func (wt *WorkspaceTracker) handleGitPollFailure(ctx context.Context, consecutiveFailures *int, cause error) bool {
|
||||
if fsdiagnostics.IsAccessDenied(cause) {
|
||||
wt.recordFilesystemFailure("workspace.git_poll", workspaceTrigger(ctx, "poll"), cause)
|
||||
*consecutiveFailures = 0
|
||||
return false
|
||||
}
|
||||
if errors.Is(cause, subproc.ErrAdmissionCanceled) {
|
||||
wt.logger.Debug("git poll admission canceled; preserving tracker liveness",
|
||||
zap.String("workDir", wt.workDir),
|
||||
@@ -150,6 +156,11 @@ func (wt *WorkspaceTracker) handleGitPollFailure(ctx context.Context, consecutiv
|
||||
}
|
||||
|
||||
probeErr := wt.runPollingGit(ctx, "rev-parse", "--git-dir")
|
||||
if fsdiagnostics.IsAccessDenied(probeErr) {
|
||||
wt.recordFilesystemFailure("workspace.git_poll", workspaceTrigger(ctx, "poll"), probeErr)
|
||||
*consecutiveFailures = 0
|
||||
return false
|
||||
}
|
||||
if errors.Is(probeErr, subproc.ErrAdmissionCanceled) {
|
||||
wt.logger.Debug("git poll health probe admission canceled; preserving tracker liveness",
|
||||
zap.String("workDir", wt.workDir),
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/agentctl/types"
|
||||
"github.com/kandev/kandev/internal/common/fsdiagnostics"
|
||||
"github.com/kandev/kandev/internal/common/subproc"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -45,7 +46,11 @@ func (wt *WorkspaceTracker) updateGitStatusClass(ctx context.Context, class subp
|
||||
if wt.isGitStatusCancellation(err) {
|
||||
wt.logger.Debug("updateGitStatus: getGitStatus canceled", zap.Error(err))
|
||||
} else {
|
||||
wt.logger.Warn("updateGitStatus: getGitStatus failed", zap.Error(err))
|
||||
if fsdiagnostics.IsAccessDenied(err) {
|
||||
wt.recordFilesystemFailure("workspace.git_status", workspaceTrigger(ctx, "poll"), err)
|
||||
} else {
|
||||
wt.logger.Warn("updateGitStatus: getGitStatus failed", zap.Error(err))
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -98,6 +103,35 @@ func (wt *WorkspaceTracker) RefreshGitStatus(ctx context.Context) {
|
||||
wt.updateGitStatusClass(ctx, subproc.GitInteractive)
|
||||
}
|
||||
|
||||
// RefreshWorkspace performs one file and Git scan for a lifecycle boundary or
|
||||
// an explicit user retry. The update lock keeps the two snapshots coherent
|
||||
// with the normal polling loops.
|
||||
func (wt *WorkspaceTracker) RefreshWorkspace(ctx context.Context, trigger string) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return
|
||||
}
|
||||
wt.clearAccessDeniedForUserOperation(trigger)
|
||||
if trigger == workspaceManualRefreshTrigger || trigger == workspaceUserSelectTrigger {
|
||||
wt.SetPollMode(PollModeFast)
|
||||
}
|
||||
ctx = withWorkspaceTrigger(ctx, trigger)
|
||||
wt.updateMu.Lock()
|
||||
defer wt.updateMu.Unlock()
|
||||
wt.updateGitStatusClass(ctx, subproc.GitInteractive)
|
||||
if err := ctx.Err(); err != nil {
|
||||
return
|
||||
}
|
||||
wt.updateFilesClass(ctx, subproc.GitInteractive)
|
||||
if err := ctx.Err(); err != nil {
|
||||
return
|
||||
}
|
||||
wt.notifyWorkspaceStreamFileChange(types.FileChangeNotification{
|
||||
Timestamp: time.Now(),
|
||||
RepositoryName: wt.repositoryName,
|
||||
Operation: types.FileOpRefresh,
|
||||
})
|
||||
}
|
||||
|
||||
// GetCurrentGitStatus returns the current cached git status. If no status has
|
||||
// been cached yet, it starts or joins a live observation without caching it.
|
||||
func (wt *WorkspaceTracker) GetCurrentGitStatus(ctx context.Context) (types.GitStatusUpdate, error) {
|
||||
|
||||
@@ -176,6 +176,9 @@ func (wt *WorkspaceTracker) monitorTick(ctx context.Context, lastState *workspac
|
||||
|
||||
currentState, err := wt.getWorkspaceState(ctx)
|
||||
if err != nil {
|
||||
if wt.accessDenied.Load() {
|
||||
return false
|
||||
}
|
||||
if !wt.workDirExists() {
|
||||
wt.logger.Warn("work directory no longer exists, stopping workspace tracker",
|
||||
zap.String("workDir", wt.workDir))
|
||||
@@ -240,8 +243,10 @@ func (wt *WorkspaceTracker) getWorkspaceState(ctx context.Context) (workspaceSta
|
||||
// to dirty files, we also include the mtime of each dirty file.
|
||||
out, stderr, err := wt.runPollingGitOutputWithStderr(ctx, "diff-files", "--name-only")
|
||||
if err != nil {
|
||||
return state, fmt.Errorf("git diff-files in %s: %w (stderr: %s)",
|
||||
wrapped := fmt.Errorf("git diff-files in %s: %w (stderr: %s)",
|
||||
wt.workDir, err, stderr)
|
||||
wt.recordFilesystemFailure("workspace.file_monitor", workspaceTrigger(ctx, "poll"), wrapped)
|
||||
return state, wrapped
|
||||
}
|
||||
state.diffFilesID = wt.buildDirtyFilesID(string(out))
|
||||
|
||||
@@ -249,6 +254,7 @@ func (wt *WorkspaceTracker) getWorkspaceState(ctx context.Context) (workspaceSta
|
||||
// The shared query excludes dependency trees before Git enumerates paths.
|
||||
untrackedID, err := wt.getUntrackedFilesID(ctx)
|
||||
if err != nil {
|
||||
wt.recordFilesystemFailure("workspace.file_monitor", workspaceTrigger(ctx, "poll"), err)
|
||||
return state, err
|
||||
}
|
||||
state.untrackedID = untrackedID
|
||||
|
||||
@@ -66,6 +66,10 @@ func TestWorkspaceTracker_MonitorExitsWhenNoGitRepo(t *testing.T) {
|
||||
// The fix should make monitorLoop exit immediately (well under 500ms).
|
||||
wt.filePollInterval = 500 * time.Millisecond
|
||||
wt.gitPollInterval = 500 * time.Millisecond
|
||||
// This test waits for the polling goroutines directly. Disable the
|
||||
// lifecycle-owned startup-grace goroutine so that the wait isolates the
|
||||
// no-git monitor behavior it is checking.
|
||||
wt.pollModeGrace = 0
|
||||
|
||||
if wt.gitIndexPath != "" {
|
||||
t.Fatalf("expected empty gitIndexPath for non-git directory, got %q", wt.gitIndexPath)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
@@ -91,6 +92,13 @@ func (wt *WorkspaceTracker) SetPollMode(mode PollMode) {
|
||||
// what the grace demotion exists to detect the absence of.
|
||||
wt.pollModePushed = true
|
||||
wt.disarmPollModeGraceLocked()
|
||||
if mode == PollModeFast {
|
||||
// Focus is an explicit visible-user retry after an access denial.
|
||||
wt.accessDenied.Store(false)
|
||||
}
|
||||
if mode == PollModeSlow && wt.accessDenied.Load() {
|
||||
mode = PollModePaused
|
||||
}
|
||||
prev := wt.pollMode
|
||||
if prev == mode {
|
||||
wt.pollModeMu.Unlock()
|
||||
@@ -102,20 +110,36 @@ func (wt *WorkspaceTracker) SetPollMode(mode PollMode) {
|
||||
wt.wakePollLoops()
|
||||
}
|
||||
|
||||
// demoteUnpushedPollMode drops the tracker to slow once pollModeGracePeriod
|
||||
// elapses with no explicit SetPollMode. Fires at most once — the timer is not
|
||||
// rearmed — so a later push always wins.
|
||||
func (wt *WorkspaceTracker) demoteUnpushedPollMode() {
|
||||
// demoteUnpushedPollMode performs the one startup-grace scan, then pauses the
|
||||
// tracker when no gateway mode ever arrived. Fires at most once — the timer is
|
||||
// not rearmed — so a later push always wins. The caller owns the context so
|
||||
// Stop can cancel both the scan and the transition before it publishes.
|
||||
func (wt *WorkspaceTracker) demoteUnpushedPollMode(ctx context.Context) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
wt.pollModeMu.Lock()
|
||||
wt.pollModeGraceTimer = nil
|
||||
if wt.pollModePushed || wt.pollMode == PollModeSlow {
|
||||
if ctx.Err() != nil || wt.pollModePushed || wt.pollMode == PollModePaused {
|
||||
wt.pollModeMu.Unlock()
|
||||
return
|
||||
}
|
||||
wt.pollMode = PollModeSlow
|
||||
wt.pollModeMu.Unlock()
|
||||
|
||||
wt.logger.Info("no poll mode pushed within grace period, demoting to slow",
|
||||
wt.RefreshWorkspace(withWorkspaceTrigger(ctx, "startup_grace"), "startup_grace")
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
|
||||
wt.pollModeMu.Lock()
|
||||
if ctx.Err() != nil || wt.pollModePushed {
|
||||
wt.pollModeMu.Unlock()
|
||||
return
|
||||
}
|
||||
wt.pollMode = PollModePaused
|
||||
wt.pollModeMu.Unlock()
|
||||
|
||||
wt.logger.Info("no poll mode pushed within grace period, final scan complete, pausing workspace polling",
|
||||
zap.Duration("grace", wt.pollModeGrace),
|
||||
zap.String("workDir", wt.workDir))
|
||||
wt.wakePollLoops()
|
||||
|
||||
@@ -2,8 +2,11 @@ package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/agentctl/types"
|
||||
)
|
||||
|
||||
// waitForPollMode polls GetPollMode until it matches want or the deadline
|
||||
@@ -66,13 +69,18 @@ func newGraceTestTracker(t *testing.T, grace time.Duration) *WorkspaceTracker {
|
||||
return wt
|
||||
}
|
||||
|
||||
// TestPollModeGrace_DemotesWhenNoPushArrives covers the leak this mechanism
|
||||
// TestPollModeGrace_FinalScansAndPausesWhenNoPushArrives covers the leak this mechanism
|
||||
// exists to close: the gateway only pushes a mode for workspaces a client
|
||||
// focuses or subscribes to, and it deliberately skips the paused push for a
|
||||
// workspace it has never pushed to. Without the grace demotion such a tracker
|
||||
// stays at the fast 2s/3s cadence for the life of the process.
|
||||
func TestPollModeGrace_DemotesWhenNoPushArrives(t *testing.T) {
|
||||
// workspace it has never pushed to. Without the grace transition such a
|
||||
// tracker stays at the fast 2s/3s cadence for the life of the process.
|
||||
func TestPollModeGrace_FinalScansAndPausesWhenNoPushArrives(t *testing.T) {
|
||||
wt := newGraceTestTracker(t, graceFiresQuickly)
|
||||
var scanCount atomic.Int32
|
||||
wt.gitStatusObserver = func(context.Context) (types.GitStatusUpdate, error) {
|
||||
scanCount.Add(1)
|
||||
return types.GitStatusUpdate{Timestamp: time.Now()}, nil
|
||||
}
|
||||
|
||||
if got := wt.GetPollMode(); got != PollModeFast {
|
||||
t.Fatalf("construction mode = %v, want %v", got, PollModeFast)
|
||||
@@ -81,7 +89,10 @@ func TestPollModeGrace_DemotesWhenNoPushArrives(t *testing.T) {
|
||||
wt.Start(context.Background())
|
||||
defer wt.Stop()
|
||||
|
||||
waitForPollMode(t, wt, PollModeSlow, 10*time.Second)
|
||||
waitForPollMode(t, wt, PollModePaused, 10*time.Second)
|
||||
if got := scanCount.Load(); got < 2 {
|
||||
t.Fatalf("git scan count = %d after grace transition, want initial and final scans", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPollModeGrace_ExplicitPushDisarmsDemotion verifies the gateway wins: once
|
||||
@@ -169,3 +180,35 @@ func TestPollModeGrace_StopDisarmsTimer(t *testing.T) {
|
||||
t.Errorf("Stop changed the poll mode to %v, want it left at %v", got, PollModeFast)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPollModeGrace_StopJoinsFinalScan verifies the timer callback is owned by
|
||||
// the tracker wait group. Stop must cancel an in-flight final scan, wait for
|
||||
// it to return, and prevent the callback from changing the mode afterward.
|
||||
func TestPollModeGrace_StopJoinsFinalScan(t *testing.T) {
|
||||
wt := newGraceTestTracker(t, graceFiresQuickly)
|
||||
var scanCount atomic.Int32
|
||||
finalScanStarted := make(chan struct{})
|
||||
finalScanFinished := make(chan struct{})
|
||||
wt.gitStatusObserver = func(ctx context.Context) (types.GitStatusUpdate, error) {
|
||||
if scanCount.Add(1) == 2 {
|
||||
close(finalScanStarted)
|
||||
<-ctx.Done()
|
||||
close(finalScanFinished)
|
||||
return types.GitStatusUpdate{}, ctx.Err()
|
||||
}
|
||||
return types.GitStatusUpdate{Timestamp: time.Now()}, nil
|
||||
}
|
||||
|
||||
wt.Start(context.Background())
|
||||
<-finalScanStarted
|
||||
wt.Stop()
|
||||
|
||||
select {
|
||||
case <-finalScanFinished:
|
||||
default:
|
||||
t.Fatal("Stop returned before the final scan exited")
|
||||
}
|
||||
if got := wt.GetPollMode(); got != PollModeFast {
|
||||
t.Fatalf("poll mode after canceled final scan = %v, want %v", got, PollModeFast)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/agentctl/types"
|
||||
"github.com/kandev/kandev/internal/common/fsdiagnostics"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/common/securityutil"
|
||||
"github.com/kandev/kandev/internal/common/subproc"
|
||||
@@ -155,6 +156,16 @@ type WorkspaceTracker struct {
|
||||
// workspace mutations while the target invariant remains atomic.
|
||||
mutationMu sync.Mutex
|
||||
|
||||
// diagnostic identity is populated by the process manager once the tracker
|
||||
// is attached to an agentctl instance. A tracker can be created before the
|
||||
// owning task/session metadata is available.
|
||||
diagnosticMu sync.RWMutex
|
||||
diagnosticTaskID string
|
||||
diagnosticSessionID string
|
||||
runtimeMode string
|
||||
filesystemWarnings *fsdiagnostics.WarningLimiter
|
||||
accessDenied atomic.Bool
|
||||
|
||||
// gitStatusObserver is the expensive live repository observation. Keeping it
|
||||
// as a dependency makes the concurrency contract deterministic to test while
|
||||
// production uses computeGitStatus.
|
||||
@@ -403,6 +414,7 @@ func newWorkspaceTracker(resolvedWorkDir, repositoryName string, log *logger.Log
|
||||
gitIndexPath: gitIndexPath,
|
||||
repositoryName: repositoryName,
|
||||
logger: log.WithFields(logFields...),
|
||||
runtimeMode: fsdiagnostics.RuntimeMode(strings.EqualFold(strings.TrimSpace(os.Getenv("KANDEV_DESKTOP_RUNTIME")), "true")),
|
||||
workspaceStreamSubscribers: make(map[types.WorkspaceStreamSubscriber]struct{}),
|
||||
filePollInterval: DefaultFilePollInterval,
|
||||
gitPollInterval: DefaultGitPollInterval,
|
||||
@@ -425,6 +437,7 @@ func newWorkspaceTracker(resolvedWorkDir, repositoryName string, log *logger.Log
|
||||
cancelCtx: ctx,
|
||||
cancelFunc: cancel,
|
||||
gitStatusObserveTimeout: workspaceGitStatusObserveTimeout,
|
||||
filesystemWarnings: fsdiagnostics.NewWarningLimiter(0),
|
||||
}
|
||||
tracker.gitStatusObserver = tracker.computeGitStatus
|
||||
return tracker
|
||||
@@ -534,6 +547,9 @@ func workDirHasOwnGitEntry(workDir string) bool {
|
||||
// so this only checks for subsequent deletion (e.g., worktree cleanup).
|
||||
func (wt *WorkspaceTracker) workDirExists() bool {
|
||||
_, err := os.Stat(wt.workDir) //nolint:gosec // workDir is validated at construction via resolveExistingWorkDir
|
||||
if err != nil && fsdiagnostics.IsAccessDenied(err) {
|
||||
wt.recordFilesystemFailure("workspace.file_monitor", "poll", err)
|
||||
}
|
||||
return !os.IsNotExist(err)
|
||||
}
|
||||
|
||||
@@ -572,7 +588,23 @@ func (wt *WorkspaceTracker) armPollModeGrace() {
|
||||
if wt.pollModePushed || wt.pollModeGraceTimer != nil || wt.pollModeGrace <= 0 {
|
||||
return
|
||||
}
|
||||
wt.pollModeGraceTimer = time.AfterFunc(wt.pollModeGrace, wt.demoteUnpushedPollMode)
|
||||
timer := time.NewTimer(wt.pollModeGrace)
|
||||
wt.pollModeGraceTimer = timer
|
||||
// The grace callback owns filesystem work, so it must be part of the
|
||||
// tracker lifecycle. A timer callback launched by time.AfterFunc cannot be
|
||||
// joined by Stop when it races with teardown.
|
||||
wt.wg.Add(1)
|
||||
go wt.pollModeGraceLoop(timer)
|
||||
}
|
||||
|
||||
func (wt *WorkspaceTracker) pollModeGraceLoop(timer *time.Timer) {
|
||||
defer wt.wg.Done()
|
||||
select {
|
||||
case <-timer.C:
|
||||
wt.demoteUnpushedPollMode(wt.cancelCtx)
|
||||
case <-wt.stopCh:
|
||||
case <-wt.cancelCtx.Done():
|
||||
}
|
||||
}
|
||||
|
||||
// disarmPollModeGraceLocked stops the fallback timer. Caller must hold pollModeMu.
|
||||
|
||||
@@ -105,6 +105,7 @@ import (
|
||||
const (
|
||||
desktopHealthTokenEnv = "KANDEV_DESKTOP_HEALTH_TOKEN"
|
||||
desktopHealthTokenHeader = "X-Kandev-Desktop-Health-Token"
|
||||
desktopRuntimeEnv = "KANDEV_DESKTOP_RUNTIME"
|
||||
agentShutdownTimeout = 20 * time.Second
|
||||
httpShutdownTimeout = 10 * time.Second
|
||||
tracingShutdownTimeout = 5 * time.Second
|
||||
@@ -1042,9 +1043,11 @@ func webRuntimeConfig(debug bool, titlePrefix string, req *http.Request) webapp.
|
||||
// Gates QA-only UI (the pseudo-locale option). Separate from Debug: the
|
||||
// e2e harness serves a PRODUCTION bundle, so the frontend cannot infer
|
||||
// this from its own build mode.
|
||||
NonProduction: profiles.DetectEnvironment() != profiles.EnvProd,
|
||||
Locale: i18n.FromRequest(req),
|
||||
TitlePrefix: strings.TrimSpace(titlePrefix),
|
||||
NonProduction: profiles.DetectEnvironment() != profiles.EnvProd,
|
||||
Locale: i18n.FromRequest(req),
|
||||
TitlePrefix: strings.TrimSpace(titlePrefix),
|
||||
NativeFolderPickerAvailable: strings.EqualFold(strings.TrimSpace(os.Getenv(desktopRuntimeEnv)), "true"),
|
||||
DesktopRuntime: strings.EqualFold(strings.TrimSpace(os.Getenv(desktopRuntimeEnv)), "true"),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -144,6 +145,7 @@ func provideServices(cfg *config.Config, log *logger.Logger, repos *Repositories
|
||||
Sessions: repos.Task,
|
||||
GitSnapshots: repos.Task,
|
||||
RepoEntities: repos.Task,
|
||||
DiscoveryRoots: repos.Task,
|
||||
RepositorySets: repos.Task,
|
||||
BranchPolicies: repos.Task,
|
||||
RepositoryCleanup: repos.Task,
|
||||
@@ -163,6 +165,7 @@ func provideServices(cfg *config.Config, log *logger.Logger, repos *Repositories
|
||||
Roots: cfg.RepositoryDiscovery.Roots,
|
||||
MaxDepth: cfg.RepositoryDiscovery.MaxDepth,
|
||||
TaskWorktreeRoots: []string{filepath.Join(cfg.ResolvedHomeDir(), "tasks")},
|
||||
DesktopRuntime: strings.EqualFold(strings.TrimSpace(os.Getenv("KANDEV_DESKTOP_RUNTIME")), "true"),
|
||||
},
|
||||
)
|
||||
taskSvc.SetPendingActionProjectionEpoch(pendingActionProjectionEpoch)
|
||||
|
||||
@@ -30,3 +30,16 @@ func TestWebRuntimeConfigOmitsBlankTitlePrefix(t *testing.T) {
|
||||
t.Fatalf("title prefix = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebRuntimeConfigAdvertisesNativeFolderPickerOnlyForDesktopRuntime(t *testing.T) {
|
||||
request := httptest.NewRequest("GET", "/", nil)
|
||||
t.Setenv("KANDEV_DESKTOP_RUNTIME", "true")
|
||||
if got := webRuntimeConfig(false, "", request).NativeFolderPickerAvailable; !got {
|
||||
t.Fatal("native folder picker should be advertised for a desktop-launched backend")
|
||||
}
|
||||
|
||||
t.Setenv("KANDEV_DESKTOP_RUNTIME", "false")
|
||||
if got := webRuntimeConfig(false, "", request).NativeFolderPickerAvailable; got {
|
||||
t.Fatal("native folder picker should not be advertised for a browser-launched backend")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,6 +115,7 @@ var startupExclusions = []CatalogExclusion{
|
||||
{EnvVar: "KANDEV_BACKEND_PID_FILE", Class: "internal wiring", Reason: "supervisor-owned process state"},
|
||||
{EnvVar: "KANDEV_DESKTOP_HEALTH_TOKEN", Class: "generated", Reason: "per-launch health authentication token"},
|
||||
{EnvVar: "KANDEV_DESKTOP_NATIVE_NOTIFICATIONS", Class: "internal wiring", Reason: "desktop shell capability handoff"},
|
||||
{EnvVar: "KANDEV_DESKTOP_RUNTIME", Class: "internal wiring", Reason: "desktop shell launch-policy handoff"},
|
||||
{EnvVar: "KANDEV_BUNDLE_DIR", Class: "packaging", Reason: "runtime bundle discovery"},
|
||||
{EnvVar: "KANDEV_WEB_DIST_DIR", Class: "packaging", Reason: "embedded web asset override"},
|
||||
{EnvVar: "KANDEV_TASK_ID", Class: "workspace injection", Reason: "task-owned child process context"},
|
||||
|
||||
@@ -135,6 +135,7 @@ func auditedStartupEnvironmentInventory() []auditedStartupEnvironment {
|
||||
{envVar: "KANDEV_BACKEND_PID_FILE", class: "exclusion"},
|
||||
{envVar: "KANDEV_DESKTOP_HEALTH_TOKEN", class: "exclusion"},
|
||||
{envVar: "KANDEV_DESKTOP_NATIVE_NOTIFICATIONS", class: "exclusion"},
|
||||
{envVar: "KANDEV_DESKTOP_RUNTIME", class: "exclusion"},
|
||||
{envVar: "KANDEV_BUNDLE_DIR", class: "exclusion"},
|
||||
{envVar: "KANDEV_WEB_DIST_DIR", class: "exclusion"},
|
||||
{envVar: "KANDEV_TASK_ID", class: "exclusion"},
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
// Package fsdiagnostics provides shared context and rate limiting for
|
||||
// filesystem access diagnostics.
|
||||
package fsdiagnostics
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const defaultWarningInterval = 30 * time.Second
|
||||
|
||||
// Context identifies one filesystem operation in a structured log entry.
|
||||
// Empty identity fields are omitted because some operations run before a
|
||||
// task or session exists.
|
||||
type Context struct {
|
||||
Operation string
|
||||
Target string
|
||||
Trigger string
|
||||
Runtime string
|
||||
WorkspaceID string
|
||||
TaskID string
|
||||
SessionID string
|
||||
PollMode string
|
||||
}
|
||||
|
||||
// Fields returns the common fields for a filesystem operation log entry.
|
||||
// Target is canonicalized here so callers that fail before their own path
|
||||
// resolver completes still produce a useful, stable diagnostic.
|
||||
func (c Context) Fields(err error) []zap.Field {
|
||||
fields := []zap.Field{
|
||||
zap.String("operation", c.Operation),
|
||||
zap.String("target", CanonicalPath(c.Target)),
|
||||
zap.String("trigger", c.Trigger),
|
||||
zap.String("runtime", c.Runtime),
|
||||
}
|
||||
if c.WorkspaceID != "" {
|
||||
fields = append(fields, zap.String("workspace_id", c.WorkspaceID))
|
||||
}
|
||||
if c.TaskID != "" {
|
||||
fields = append(fields, zap.String("task_id", c.TaskID))
|
||||
}
|
||||
if c.SessionID != "" {
|
||||
fields = append(fields, zap.String("session_id", c.SessionID))
|
||||
}
|
||||
if c.PollMode != "" {
|
||||
fields = append(fields, zap.String("poll_mode", c.PollMode))
|
||||
}
|
||||
if err != nil {
|
||||
fields = append(fields, zap.Error(err))
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
// CanonicalPath returns an absolute, cleaned path and resolves symlinks when
|
||||
// the target currently exists. It deliberately preserves a blank target.
|
||||
func CanonicalPath(path string) string {
|
||||
path = strings.TrimSpace(path)
|
||||
if path == "" {
|
||||
return ""
|
||||
}
|
||||
abs, err := filepath.Abs(filepath.Clean(path))
|
||||
if err != nil {
|
||||
return filepath.Clean(path)
|
||||
}
|
||||
if resolved, err := filepath.EvalSymlinks(abs); err == nil {
|
||||
return filepath.Clean(resolved)
|
||||
}
|
||||
return filepath.Clean(abs)
|
||||
}
|
||||
|
||||
// RuntimeMode converts the desktop-process marker into the stable runtime
|
||||
// labels used by diagnostics.
|
||||
func RuntimeMode(desktop bool) string {
|
||||
if desktop {
|
||||
return "desktop"
|
||||
}
|
||||
return "server"
|
||||
}
|
||||
|
||||
// IsAccessDenied reports the deterministic permission class used by the
|
||||
// tracker pause policy. The text fallback covers platform-specific errors
|
||||
// that do not wrap os.ErrPermission in tests or in an OS adapter.
|
||||
func IsAccessDenied(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, os.ErrPermission) {
|
||||
return true
|
||||
}
|
||||
message := strings.ToLower(err.Error())
|
||||
return strings.Contains(message, "permission denied") ||
|
||||
strings.Contains(message, "access is denied") ||
|
||||
strings.Contains(message, "operation not permitted")
|
||||
}
|
||||
|
||||
type warningState struct {
|
||||
lastWarned time.Time
|
||||
suppressed int
|
||||
}
|
||||
|
||||
// WarningLimiter bounds repeated warnings for an identical operation. The
|
||||
// first warning is emitted immediately; the next warning after the interval
|
||||
// carries the number suppressed since the previous warning.
|
||||
type WarningLimiter struct {
|
||||
mu sync.Mutex
|
||||
interval time.Duration
|
||||
now func() time.Time
|
||||
entries map[string]warningState
|
||||
}
|
||||
|
||||
// NewWarningLimiter creates a limiter with the supplied warning interval.
|
||||
// Non-positive intervals use the production default.
|
||||
func NewWarningLimiter(interval time.Duration) *WarningLimiter {
|
||||
if interval <= 0 {
|
||||
interval = defaultWarningInterval
|
||||
}
|
||||
return &WarningLimiter{
|
||||
interval: interval,
|
||||
now: time.Now,
|
||||
entries: make(map[string]warningState),
|
||||
}
|
||||
}
|
||||
|
||||
// Warn emits a bounded warning with the operation context. The error text is
|
||||
// intentionally excluded from the key so changing OS details cannot create an
|
||||
// unbounded number of entries for one operation and target.
|
||||
func (l *WarningLimiter) Warn(log *zap.Logger, message string, operation Context, err error) {
|
||||
if l == nil || log == nil {
|
||||
return
|
||||
}
|
||||
|
||||
now := l.now()
|
||||
key := warningKey(operation)
|
||||
l.mu.Lock()
|
||||
state, exists := l.entries[key]
|
||||
if exists && now.Sub(state.lastWarned) < l.interval {
|
||||
state.suppressed++
|
||||
l.entries[key] = state
|
||||
l.mu.Unlock()
|
||||
return
|
||||
}
|
||||
suppressed := state.suppressed
|
||||
l.entries[key] = warningState{lastWarned: now}
|
||||
l.mu.Unlock()
|
||||
|
||||
fields := operation.Fields(err)
|
||||
if suppressed > 0 {
|
||||
fields = append(fields, zap.Int("suppressed_count", suppressed))
|
||||
}
|
||||
log.Warn(message, fields...)
|
||||
}
|
||||
|
||||
func warningKey(operation Context) string {
|
||||
return strings.Join([]string{
|
||||
operation.Operation,
|
||||
CanonicalPath(operation.Target),
|
||||
operation.Trigger,
|
||||
operation.Runtime,
|
||||
operation.WorkspaceID,
|
||||
operation.TaskID,
|
||||
operation.SessionID,
|
||||
}, "\x00")
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package fsdiagnostics
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"go.uber.org/zap/zaptest/observer"
|
||||
)
|
||||
|
||||
func TestWarningLimiterBoundsRepeatedAccessDenials(t *testing.T) {
|
||||
core, logs := observer.New(zapcore.WarnLevel)
|
||||
clock := time.Date(2026, time.August, 27, 12, 0, 0, 0, time.UTC)
|
||||
limiter := NewWarningLimiter(time.Minute)
|
||||
limiter.now = func() time.Time { return clock }
|
||||
operation := Context{
|
||||
Operation: "repository.discovery.scan",
|
||||
Target: filepath.Join(t.TempDir(), "repo"),
|
||||
Trigger: "poll",
|
||||
Runtime: "desktop",
|
||||
WorkspaceID: "workspace-1",
|
||||
TaskID: "task-1",
|
||||
SessionID: "session-1",
|
||||
PollMode: "slow",
|
||||
}
|
||||
denied := errors.New("permission denied")
|
||||
|
||||
for range 3 {
|
||||
limiter.Warn(zap.New(core), "filesystem.access_denied", operation, denied)
|
||||
}
|
||||
if got := logs.Len(); got != 1 {
|
||||
t.Fatalf("warning count before interval = %d, want 1", got)
|
||||
}
|
||||
|
||||
clock = clock.Add(time.Minute)
|
||||
limiter.Warn(zap.New(core), "filesystem.access_denied", operation, denied)
|
||||
if got := logs.Len(); got != 2 {
|
||||
t.Fatalf("warning count after interval = %d, want 2", got)
|
||||
}
|
||||
if got := logs.All()[1].ContextMap()["suppressed_count"]; got != int64(2) {
|
||||
t.Fatalf("suppressed_count = %v, want 2", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWarningLimiterDoesNotGrowPerErrorMessage(t *testing.T) {
|
||||
core, logs := observer.New(zapcore.WarnLevel)
|
||||
limiter := NewWarningLimiter(time.Minute)
|
||||
operation := Context{
|
||||
Operation: "workspace.file_monitor",
|
||||
Target: filepath.Join(t.TempDir(), "repo"),
|
||||
Trigger: "poll",
|
||||
Runtime: "desktop",
|
||||
}
|
||||
|
||||
limiter.Warn(zap.New(core), "filesystem.access_denied", operation, errors.New("permission denied: one"))
|
||||
limiter.Warn(zap.New(core), "filesystem.access_denied", operation, errors.New("permission denied: two"))
|
||||
|
||||
if got := logs.Len(); got != 1 {
|
||||
t.Fatalf("warning count for changing errors = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextFieldsCanonicalizeTargetAndIncludeIdentity(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
operation := Context{
|
||||
Operation: "workspace.file_monitor",
|
||||
Target: filepath.Join(root, ".", "repo"),
|
||||
Trigger: "stale_refresh",
|
||||
Runtime: "server",
|
||||
WorkspaceID: "workspace-1",
|
||||
TaskID: "task-1",
|
||||
SessionID: "session-1",
|
||||
PollMode: "fast",
|
||||
}
|
||||
fields := operation.Fields(errors.New("permission denied"))
|
||||
core, logs := observer.New(zapcore.WarnLevel)
|
||||
zap.New(core).Warn("filesystem.access_denied", fields...)
|
||||
entry := logs.All()[0].ContextMap()
|
||||
|
||||
if got, want := entry["operation"], "workspace.file_monitor"; got != want {
|
||||
t.Fatalf("operation = %v, want %v", got, want)
|
||||
}
|
||||
if got, want := entry["target"], CanonicalPath(operation.Target); got != want {
|
||||
t.Fatalf("target = %v, want %v", got, want)
|
||||
}
|
||||
for key, want := range map[string]string{
|
||||
"trigger": "stale_refresh",
|
||||
"runtime": "server",
|
||||
"workspace_id": "workspace-1",
|
||||
"task_id": "task-1",
|
||||
"session_id": "session-1",
|
||||
"poll_mode": "fast",
|
||||
} {
|
||||
if got := entry[key]; got != want {
|
||||
t.Errorf("%s = %v, want %v", key, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsAccessDenied(t *testing.T) {
|
||||
if !IsAccessDenied(errors.New("permission denied")) {
|
||||
t.Error("permission denied was not classified as access denied")
|
||||
}
|
||||
if IsAccessDenied(errors.New("temporary index lock")) {
|
||||
t.Error("index lock was classified as access denied")
|
||||
}
|
||||
}
|
||||
@@ -536,7 +536,7 @@ func (c *MockController) setMergeOutcome(ctx *gin.Context) {
|
||||
switch req.Outcome {
|
||||
case "failed":
|
||||
c.mock.SetMergeFailure(req.Owner, req.Repo, req.Number, "mock merge provider unavailable")
|
||||
case "pending":
|
||||
case computedReviewStatePending:
|
||||
c.mock.SetMergeFailure(req.Owner, req.Repo, req.Number, "mock merge request remained pending")
|
||||
case "head_mismatch":
|
||||
c.mock.SetMergeFailure(req.Owner, req.Repo, req.Number, "mock merge head mismatch")
|
||||
@@ -548,7 +548,7 @@ func (c *MockController) setMergeOutcome(ctx *gin.Context) {
|
||||
|
||||
func validMockMergeOutcome(outcome string) bool {
|
||||
switch outcome {
|
||||
case string(MergeOutcomeMerged), string(MergeOutcomeQueued), "failed", "pending", "head_mismatch":
|
||||
case string(MergeOutcomeMerged), string(MergeOutcomeQueued), "failed", computedReviewStatePending, "head_mismatch":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
|
||||
@@ -189,6 +189,7 @@ func allowedSupervisorEnv(env []string) map[string]string {
|
||||
"KANDEV_DATABASE_PATH": true,
|
||||
"KANDEV_SERVER_PORT": true,
|
||||
"KANDEV_DESKTOP_HEALTH_TOKEN": true,
|
||||
"KANDEV_DESKTOP_RUNTIME": true,
|
||||
"KANDEV_WEB_INTERNAL_URL": true,
|
||||
"KANDEV_AGENT_STANDALONE_PORT": true,
|
||||
"KANDEV_LOG_LEVEL": true,
|
||||
|
||||
@@ -599,9 +599,26 @@ type LocalRepositoryDTO struct {
|
||||
}
|
||||
|
||||
type RepositoryDiscoveryResponse struct {
|
||||
Roots []string `json:"roots"`
|
||||
Repositories []LocalRepositoryDTO `json:"repositories"`
|
||||
Total int `json:"total"`
|
||||
Roots []string `json:"roots"`
|
||||
Repositories []LocalRepositoryDTO `json:"repositories"`
|
||||
Total int `json:"total"`
|
||||
DesktopRuntime bool `json:"desktop_runtime"`
|
||||
RootStates []DesktopDiscoveryRootDTO `json:"root_states"`
|
||||
ScanTime *time.Time `json:"scan_time,omitempty"`
|
||||
Refreshing bool `json:"refreshing"`
|
||||
Cached bool `json:"cached"`
|
||||
HomeConfirmationRequired bool `json:"home_confirmation_required"`
|
||||
FailedRoots []string `json:"failed_roots,omitempty"`
|
||||
}
|
||||
|
||||
type DesktopDiscoveryRootDTO struct {
|
||||
ID string `json:"id"`
|
||||
Path string `json:"path"`
|
||||
DisplayPath string `json:"display_path"`
|
||||
State string `json:"state"`
|
||||
LastScanAt *time.Time `json:"last_scan_at,omitempty"`
|
||||
LastFailureAt *time.Time `json:"last_failure_at,omitempty"`
|
||||
LastFailureCode string `json:"last_failure_code,omitempty"`
|
||||
}
|
||||
|
||||
type RepositoryPathValidationResponse struct {
|
||||
@@ -818,6 +835,18 @@ func FromLocalRepository(repo service.LocalRepository) LocalRepositoryDTO {
|
||||
}
|
||||
}
|
||||
|
||||
func FromDesktopDiscoveryRoot(root models.DesktopDiscoveryRoot) DesktopDiscoveryRootDTO {
|
||||
return DesktopDiscoveryRootDTO{
|
||||
ID: root.ID,
|
||||
Path: root.Path,
|
||||
DisplayPath: root.DisplayPath,
|
||||
State: string(root.State),
|
||||
LastScanAt: root.LastScanAt,
|
||||
LastFailureAt: root.LastFailureAt,
|
||||
LastFailureCode: root.LastFailureCode,
|
||||
}
|
||||
}
|
||||
|
||||
func FromTask(task *models.Task) TaskDTO {
|
||||
return FromTaskWithPrimarySession(task, nil)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/kandev/kandev/internal/task/dto"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/repository"
|
||||
"github.com/kandev/kandev/internal/task/repository/repoerrors"
|
||||
"github.com/kandev/kandev/internal/task/service"
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
"go.uber.org/zap"
|
||||
@@ -41,6 +42,12 @@ func (h *RepositoryHandlers) registerHTTP(router *gin.Engine) {
|
||||
api.POST("/workspaces/:id/repositories", h.httpCreateRepository)
|
||||
api.POST("/workspaces/:id/repositories/initialize-local", h.httpInitializeLocalRepository)
|
||||
api.GET("/workspaces/:id/repositories/discover", h.httpDiscoverRepositories)
|
||||
api.GET("/workspaces/:id/repositories/discovery", h.httpGetDiscoverySnapshot)
|
||||
api.POST("/workspaces/:id/repositories/discovery/refresh", h.httpRefreshDiscovery)
|
||||
api.GET("/repositories/discovery/roots", h.httpListDiscoveryRoots)
|
||||
api.POST("/repositories/discovery/roots", h.httpAddDiscoveryRoot)
|
||||
api.POST("/repositories/discovery/roots/reconnect", h.httpReconnectDiscoveryRoot)
|
||||
api.DELETE("/repositories/discovery/roots", h.httpRemoveDiscoveryRoot)
|
||||
// Unified branch listing — accepts either ?repository_id= for an imported
|
||||
// workspace repo, or ?path= for an on-machine folder discovered but not
|
||||
// yet imported. Both paths bottom out in `listGitBranches`; the only
|
||||
@@ -118,27 +125,145 @@ func (h *RepositoryHandlers) httpListRepositories(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (h *RepositoryHandlers) httpDiscoverRepositories(c *gin.Context) {
|
||||
workspaceID := c.Param("id")
|
||||
root := c.Query("root")
|
||||
result, err := h.service.DiscoverLocalRepositories(c.Request.Context(), root)
|
||||
result, err := h.service.DiscoverLocalRepositoriesForWorkspace(
|
||||
c.Request.Context(), workspaceID, root,
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrPathNotAllowed) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "root is not within allowed paths"})
|
||||
return
|
||||
}
|
||||
h.logger.Error("failed to discover repositories", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to discover repositories"})
|
||||
h.writeDiscoveryError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
resp := dto.RepositoryDiscoveryResponse{
|
||||
Roots: result.Roots,
|
||||
Repositories: make([]dto.LocalRepositoryDTO, 0, len(result.Repositories)),
|
||||
Total: len(result.Repositories),
|
||||
c.JSON(http.StatusOK, discoveryResponse(result))
|
||||
}
|
||||
|
||||
func (h *RepositoryHandlers) httpGetDiscoverySnapshot(c *gin.Context) {
|
||||
result, err := h.service.GetLocalRepositoryDiscoveryForWorkspace(
|
||||
c.Request.Context(), c.Param("id"), c.Query("root"),
|
||||
)
|
||||
if err != nil {
|
||||
h.writeDiscoveryError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, discoveryResponse(result))
|
||||
}
|
||||
|
||||
func (h *RepositoryHandlers) httpRefreshDiscovery(c *gin.Context) {
|
||||
result, err := h.service.RefreshLocalRepositoryDiscoveryForWorkspaceWithTrigger(
|
||||
c.Request.Context(),
|
||||
c.Param("id"),
|
||||
c.Query("root"),
|
||||
service.NormalizeRepositoryDiscoveryTrigger(c.Query("trigger")),
|
||||
)
|
||||
if err != nil {
|
||||
h.writeDiscoveryError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, discoveryResponse(result))
|
||||
}
|
||||
|
||||
func discoveryResponse(result service.RepositoryDiscoveryResult) dto.RepositoryDiscoveryResponse {
|
||||
rootStates := make([]dto.DesktopDiscoveryRootDTO, 0, len(result.RootStates))
|
||||
for _, root := range result.RootStates {
|
||||
rootStates = append(rootStates, dto.FromDesktopDiscoveryRoot(root))
|
||||
}
|
||||
repositories := make([]dto.LocalRepositoryDTO, 0, len(result.Repositories))
|
||||
for _, repo := range result.Repositories {
|
||||
resp.Repositories = append(resp.Repositories, dto.FromLocalRepository(repo))
|
||||
repositories = append(repositories, dto.FromLocalRepository(repo))
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
return dto.RepositoryDiscoveryResponse{
|
||||
Roots: result.Roots,
|
||||
Repositories: repositories,
|
||||
Total: len(repositories),
|
||||
DesktopRuntime: result.DesktopRuntime,
|
||||
RootStates: rootStates,
|
||||
ScanTime: result.ScanTime,
|
||||
Refreshing: result.Refreshing,
|
||||
Cached: result.Cached,
|
||||
HomeConfirmationRequired: result.HomeConfirmationRequired,
|
||||
FailedRoots: result.FailedRoots,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *RepositoryHandlers) writeDiscoveryError(c *gin.Context, err error) {
|
||||
switch {
|
||||
case errors.Is(err, repoerrors.ErrWorkspaceNotFound):
|
||||
handleNotFound(c, h.logger, err, "workspace not found")
|
||||
case errors.Is(err, service.ErrPathNotAllowed), errors.Is(err, service.ErrInvalidDiscoveryRoot):
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
case errors.Is(err, service.ErrDesktopDiscoveryUnavailable):
|
||||
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
|
||||
default:
|
||||
h.logger.Error("failed to load repository discovery", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load repository discovery"})
|
||||
}
|
||||
}
|
||||
|
||||
type discoveryRootRequest struct {
|
||||
Path string `json:"path"`
|
||||
NewPath string `json:"new_path"`
|
||||
}
|
||||
|
||||
func (h *RepositoryHandlers) httpListDiscoveryRoots(c *gin.Context) {
|
||||
roots, err := h.service.ListDesktopDiscoveryRoots(c.Request.Context())
|
||||
if err != nil {
|
||||
h.writeDiscoveryError(c, err)
|
||||
return
|
||||
}
|
||||
response := make([]dto.DesktopDiscoveryRootDTO, 0, len(roots))
|
||||
for _, root := range roots {
|
||||
if root != nil {
|
||||
response = append(response, dto.FromDesktopDiscoveryRoot(*root))
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"roots": response})
|
||||
}
|
||||
|
||||
func (h *RepositoryHandlers) httpAddDiscoveryRoot(c *gin.Context) {
|
||||
var body discoveryRootRequest
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
root, err := h.service.AddDesktopDiscoveryRoot(c.Request.Context(), body.Path)
|
||||
if err != nil {
|
||||
h.writeDiscoveryError(c, err)
|
||||
return
|
||||
}
|
||||
if root == nil {
|
||||
h.logger.Error("desktop discovery root was not returned after add")
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to add discovery root"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.FromDesktopDiscoveryRoot(*root))
|
||||
}
|
||||
|
||||
func (h *RepositoryHandlers) httpReconnectDiscoveryRoot(c *gin.Context) {
|
||||
var body discoveryRootRequest
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
root, err := h.service.ReconnectDesktopDiscoveryRoot(c.Request.Context(), body.Path, body.NewPath)
|
||||
if err != nil {
|
||||
h.writeDiscoveryError(c, err)
|
||||
return
|
||||
}
|
||||
if root == nil {
|
||||
h.logger.Error("desktop discovery root was not returned after reconnect")
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to reconnect discovery root"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.FromDesktopDiscoveryRoot(*root))
|
||||
}
|
||||
|
||||
func (h *RepositoryHandlers) httpRemoveDiscoveryRoot(c *gin.Context) {
|
||||
if err := h.service.RemoveDesktopDiscoveryRoot(c.Request.Context(), c.Query("path")); err != nil {
|
||||
h.writeDiscoveryError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// httpListDirectory lists the immediate subdirectories of ?path= (defaults
|
||||
|
||||
@@ -416,6 +416,59 @@ func TestHTTPListBranchesRejectsInvalidExplicitPath(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPDesktopDiscoveryRootLifecycle(t *testing.T) {
|
||||
router, repo, _ := newDesktopRepositoryHTTPTestRouter(t)
|
||||
rootPath := canonicalTempDir(t)
|
||||
|
||||
request := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/v1/repositories/discovery/roots",
|
||||
strings.NewReader(`{"path":`+strconv.Quote(rootPath)+`}`),
|
||||
)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("add status = %d, want %d; body = %s", response.Code, http.StatusCreated, response.Body.String())
|
||||
}
|
||||
if !strings.Contains(response.Body.String(), strconv.Quote(rootPath)) {
|
||||
t.Fatalf("add response does not contain root path %q: %s", rootPath, response.Body.String())
|
||||
}
|
||||
|
||||
listResponse := httptest.NewRecorder()
|
||||
router.ServeHTTP(listResponse, httptest.NewRequest(http.MethodGet, "/api/v1/repositories/discovery/roots", nil))
|
||||
if listResponse.Code != http.StatusOK || !strings.Contains(listResponse.Body.String(), strconv.Quote(rootPath)) {
|
||||
t.Fatalf("list status/body = %d/%s", listResponse.Code, listResponse.Body.String())
|
||||
}
|
||||
|
||||
snapshotResponse := httptest.NewRecorder()
|
||||
router.ServeHTTP(snapshotResponse, httptest.NewRequest(
|
||||
http.MethodGet,
|
||||
"/api/v1/workspaces/ws-1/repositories/discovery",
|
||||
nil,
|
||||
))
|
||||
if snapshotResponse.Code != http.StatusOK || !strings.Contains(snapshotResponse.Body.String(), `"desktop_runtime":true`) {
|
||||
t.Fatalf("snapshot status/body = %d/%s", snapshotResponse.Code, snapshotResponse.Body.String())
|
||||
}
|
||||
|
||||
removeResponse := httptest.NewRecorder()
|
||||
router.ServeHTTP(removeResponse, httptest.NewRequest(
|
||||
http.MethodDelete,
|
||||
"/api/v1/repositories/discovery/roots?path="+url.QueryEscape(rootPath),
|
||||
nil,
|
||||
))
|
||||
if removeResponse.Code != http.StatusNoContent {
|
||||
t.Fatalf("remove status = %d, want %d; body = %s", removeResponse.Code, http.StatusNoContent, removeResponse.Body.String())
|
||||
}
|
||||
roots, err := repo.ListDesktopDiscoveryRoots(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("list roots after remove: %v", err)
|
||||
}
|
||||
if len(roots) != 0 {
|
||||
t.Fatalf("roots after remove = %+v, want none", roots)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPLocalRepositoryStatusRejectsInvalidExplicitPath(t *testing.T) {
|
||||
router, _ := newRepositoryHTTPTestRouter(t)
|
||||
request := httptest.NewRequest(
|
||||
@@ -439,6 +492,14 @@ func newRepositoryHTTPTestRouter(t *testing.T) (*gin.Engine, *taskrepo.Repositor
|
||||
}
|
||||
|
||||
func newRepositoryHTTPTestRouterWithService(t *testing.T) (*gin.Engine, *taskrepo.Repository, *service.Service) {
|
||||
return newRepositoryHTTPTestRouterWithConfig(t, service.RepositoryDiscoveryConfig{})
|
||||
}
|
||||
|
||||
func newDesktopRepositoryHTTPTestRouter(t *testing.T) (*gin.Engine, *taskrepo.Repository, *service.Service) {
|
||||
return newRepositoryHTTPTestRouterWithConfig(t, service.RepositoryDiscoveryConfig{DesktopRuntime: true})
|
||||
}
|
||||
|
||||
func newRepositoryHTTPTestRouterWithConfig(t *testing.T, discoveryConfig service.RepositoryDiscoveryConfig) (*gin.Engine, *taskrepo.Repository, *service.Service) {
|
||||
t.Helper()
|
||||
dbConn, err := db.OpenSQLite(filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
@@ -466,9 +527,10 @@ func newRepositoryHTTPTestRouterWithService(t *testing.T) (*gin.Engine, *taskrep
|
||||
}
|
||||
eventBus := bus.NewMemoryEventBus(log)
|
||||
svc := service.NewService(service.Repos{
|
||||
Workspaces: repo,
|
||||
RepoEntities: repo,
|
||||
}, eventBus, log, service.RepositoryDiscoveryConfig{})
|
||||
Workspaces: repo,
|
||||
RepoEntities: repo,
|
||||
DiscoveryRoots: repo,
|
||||
}, eventBus, log, discoveryConfig)
|
||||
router := gin.New()
|
||||
NewRepositoryHandlers(svc, log).registerHTTP(router)
|
||||
return router, repo, svc
|
||||
|
||||
@@ -174,6 +174,12 @@ func TestRegisterRepositoryRoutesWiresHTTPAndWS(t *testing.T) {
|
||||
"POST /api/v1/workspaces/:id/repositories",
|
||||
"POST /api/v1/workspaces/:id/repositories/initialize-local",
|
||||
"GET /api/v1/workspaces/:id/repositories/discover",
|
||||
"GET /api/v1/workspaces/:id/repositories/discovery",
|
||||
"POST /api/v1/workspaces/:id/repositories/discovery/refresh",
|
||||
"GET /api/v1/repositories/discovery/roots",
|
||||
"POST /api/v1/repositories/discovery/roots",
|
||||
"POST /api/v1/repositories/discovery/roots/reconnect",
|
||||
"DELETE /api/v1/repositories/discovery/roots",
|
||||
"GET /api/v1/workspaces/:id/branches",
|
||||
"GET /api/v1/workspaces/:id/repositories/local-status",
|
||||
"GET /api/v1/workspaces/:id/repositories/validate",
|
||||
|
||||
@@ -1816,6 +1816,37 @@ type Repository struct {
|
||||
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||
}
|
||||
|
||||
// DesktopDiscoveryRootState describes whether an install-wide discovery root
|
||||
// can currently be read by the backend process.
|
||||
type DesktopDiscoveryRootState string
|
||||
|
||||
const (
|
||||
DesktopDiscoveryRootConnected DesktopDiscoveryRootState = "connected"
|
||||
DesktopDiscoveryRootReconnectRequired DesktopDiscoveryRootState = "reconnect_required"
|
||||
)
|
||||
|
||||
// DesktopDiscoveryRoot is an install-wide root selected for automatic local
|
||||
// repository discovery. It is deliberately separate from a workspace-owned
|
||||
// repository grant.
|
||||
type DesktopDiscoveryRoot struct {
|
||||
ID string `json:"id"`
|
||||
Path string `json:"path"`
|
||||
DisplayPath string `json:"display_path"`
|
||||
State DesktopDiscoveryRootState `json:"state"`
|
||||
LastScanAt *time.Time `json:"last_scan_at,omitempty"`
|
||||
LastFailureAt *time.Time `json:"last_failure_at,omitempty"`
|
||||
LastFailureCode string `json:"last_failure_code,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// DesktopDiscoveryMigration records upgrade-only state without turning the
|
||||
// old implicit Home fallback into a new automatic scan.
|
||||
type DesktopDiscoveryMigration struct {
|
||||
HomeConfirmationRequired bool `json:"home_confirmation_required"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// RepositoryBranchPolicy is a reusable branch workflow owned by one repository.
|
||||
// It is configuration, not task history: task repositories copy these fields
|
||||
// into their snapshot columns when a policy is selected.
|
||||
|
||||
@@ -457,6 +457,18 @@ type RepositoryEntityRepository interface {
|
||||
GetRepositoryByLocalPath(ctx context.Context, workspaceID, localPath string) (*models.Repository, error)
|
||||
}
|
||||
|
||||
// DesktopDiscoveryRootRepository stores install-wide desktop discovery roots
|
||||
// and one-time migration state. These records are not owned by a workspace.
|
||||
type DesktopDiscoveryRootRepository interface {
|
||||
ListDesktopDiscoveryRoots(ctx context.Context) ([]*models.DesktopDiscoveryRoot, error)
|
||||
GetDesktopDiscoveryRoot(ctx context.Context, path string) (*models.DesktopDiscoveryRoot, error)
|
||||
CreateDesktopDiscoveryRoot(ctx context.Context, root *models.DesktopDiscoveryRoot) error
|
||||
UpdateDesktopDiscoveryRoot(ctx context.Context, root *models.DesktopDiscoveryRoot) error
|
||||
DeleteDesktopDiscoveryRoot(ctx context.Context, path string) error
|
||||
GetDesktopDiscoveryMigration(ctx context.Context) (*models.DesktopDiscoveryMigration, error)
|
||||
SetDesktopDiscoveryMigration(ctx context.Context, migration *models.DesktopDiscoveryMigration) error
|
||||
}
|
||||
|
||||
// RepositorySetRepository stores named, reusable groups of workspace
|
||||
// repositories. Membership order is authoritative: writes assign contiguous
|
||||
// positions from the supplied order, and reads return items in that order with
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
// added without growing the function's cyclomatic complexity.
|
||||
func (r *Repository) initSchema() error {
|
||||
steps := []func() error{
|
||||
r.initDesktopDiscoverySchema,
|
||||
r.initCoreSchema,
|
||||
r.initRepositorySetsSchema,
|
||||
r.initRepositoryBranchPoliciesSchema,
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/kandev/kandev/internal/db/dialect"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/repository/repoerrors"
|
||||
)
|
||||
|
||||
const desktopDiscoverySchemaDDL = `
|
||||
CREATE TABLE IF NOT EXISTS desktop_discovery_roots (
|
||||
id TEXT PRIMARY KEY,
|
||||
path TEXT NOT NULL UNIQUE,
|
||||
display_path TEXT NOT NULL DEFAULT '',
|
||||
state TEXT NOT NULL DEFAULT 'connected',
|
||||
last_scan_at TIMESTAMP,
|
||||
last_failure_at TIMESTAMP,
|
||||
last_failure_code TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMP NOT NULL,
|
||||
updated_at TIMESTAMP NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_desktop_discovery_roots_state
|
||||
ON desktop_discovery_roots(state);
|
||||
CREATE TABLE IF NOT EXISTS desktop_discovery_migration (
|
||||
id INTEGER PRIMARY KEY,
|
||||
home_confirmation_required INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at TIMESTAMP NOT NULL
|
||||
);
|
||||
`
|
||||
|
||||
func (r *Repository) initDesktopDiscoverySchema() error {
|
||||
legacyInstallation, err := r.tableExists("workspaces")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := r.db.Exec(desktopDiscoverySchemaDDL); err != nil {
|
||||
return err
|
||||
}
|
||||
required := 0
|
||||
if legacyInstallation {
|
||||
required = 1
|
||||
}
|
||||
_, err = r.db.Exec(r.db.Rebind(`
|
||||
INSERT INTO desktop_discovery_migration (id, home_confirmation_required, updated_at)
|
||||
VALUES (1, ?, ?)
|
||||
ON CONFLICT (id) DO NOTHING
|
||||
`), required, time.Now().UTC())
|
||||
return err
|
||||
}
|
||||
|
||||
const desktopDiscoveryRootColumns = `id, path, display_path, state, last_scan_at, last_failure_at, last_failure_code, created_at, updated_at`
|
||||
|
||||
func (r *Repository) scanDesktopDiscoveryRoot(scanner interface{ Scan(...any) error }) (*models.DesktopDiscoveryRoot, error) {
|
||||
root := &models.DesktopDiscoveryRoot{}
|
||||
var state string
|
||||
var lastScanAt, lastFailureAt sql.NullTime
|
||||
if err := scanner.Scan(
|
||||
&root.ID, &root.Path, &root.DisplayPath, &state,
|
||||
&lastScanAt, &lastFailureAt, &root.LastFailureCode,
|
||||
&root.CreatedAt, &root.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
root.State = models.DesktopDiscoveryRootState(state)
|
||||
if lastScanAt.Valid {
|
||||
value := lastScanAt.Time
|
||||
root.LastScanAt = &value
|
||||
}
|
||||
if lastFailureAt.Valid {
|
||||
value := lastFailureAt.Time
|
||||
root.LastFailureAt = &value
|
||||
}
|
||||
return root, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListDesktopDiscoveryRoots(ctx context.Context) ([]*models.DesktopDiscoveryRoot, error) {
|
||||
rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(`
|
||||
SELECT `+desktopDiscoveryRootColumns+` FROM desktop_discovery_roots
|
||||
ORDER BY LOWER(display_path), path
|
||||
`))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
roots := make([]*models.DesktopDiscoveryRoot, 0)
|
||||
for rows.Next() {
|
||||
root, err := r.scanDesktopDiscoveryRoot(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
roots = append(roots, root)
|
||||
}
|
||||
return roots, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) GetDesktopDiscoveryRoot(ctx context.Context, path string) (*models.DesktopDiscoveryRoot, error) {
|
||||
root, err := r.scanDesktopDiscoveryRoot(r.ro.QueryRowContext(ctx, r.ro.Rebind(
|
||||
`SELECT `+desktopDiscoveryRootColumns+` FROM desktop_discovery_roots WHERE path = ?`,
|
||||
), path))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return root, err
|
||||
}
|
||||
|
||||
func (r *Repository) CreateDesktopDiscoveryRoot(ctx context.Context, root *models.DesktopDiscoveryRoot) error {
|
||||
if root.ID == "" {
|
||||
root.ID = uuid.NewString()
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
root.CreatedAt = now
|
||||
root.UpdatedAt = now
|
||||
if root.State == "" {
|
||||
root.State = models.DesktopDiscoveryRootConnected
|
||||
}
|
||||
_, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
INSERT INTO desktop_discovery_roots (
|
||||
id, path, display_path, state, last_scan_at, last_failure_at,
|
||||
last_failure_code, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`), root.ID, root.Path, root.DisplayPath, root.State, root.LastScanAt,
|
||||
root.LastFailureAt, root.LastFailureCode, root.CreatedAt, root.UpdatedAt)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateDesktopDiscoveryRoot(ctx context.Context, root *models.DesktopDiscoveryRoot) error {
|
||||
root.UpdatedAt = time.Now().UTC()
|
||||
result, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
UPDATE desktop_discovery_roots
|
||||
SET path = ?, display_path = ?, state = ?, last_scan_at = ?,
|
||||
last_failure_at = ?, last_failure_code = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`), root.Path, root.DisplayPath, root.State, root.LastScanAt, root.LastFailureAt,
|
||||
root.LastFailureCode, root.UpdatedAt, root.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
count, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
return repoerrors.ErrRepositoryNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteDesktopDiscoveryRoot(ctx context.Context, path string) error {
|
||||
_, err := r.db.ExecContext(ctx, r.db.Rebind(`DELETE FROM desktop_discovery_roots WHERE path = ?`), path)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) GetDesktopDiscoveryMigration(ctx context.Context) (*models.DesktopDiscoveryMigration, error) {
|
||||
migration := &models.DesktopDiscoveryMigration{}
|
||||
var required int
|
||||
err := r.ro.QueryRowContext(ctx, r.ro.Rebind(`
|
||||
SELECT home_confirmation_required, updated_at
|
||||
FROM desktop_discovery_migration WHERE id = 1
|
||||
`)).Scan(&required, &migration.UpdatedAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return migration, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
migration.HomeConfirmationRequired = required != 0
|
||||
return migration, nil
|
||||
}
|
||||
|
||||
func (r *Repository) SetDesktopDiscoveryMigration(ctx context.Context, migration *models.DesktopDiscoveryMigration) error {
|
||||
migration.UpdatedAt = time.Now().UTC()
|
||||
_, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
INSERT INTO desktop_discovery_migration (id, home_confirmation_required, updated_at)
|
||||
VALUES (1, ?, ?)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
home_confirmation_required = excluded.home_confirmation_required,
|
||||
updated_at = excluded.updated_at
|
||||
`), dialect.BoolToInt(migration.HomeConfirmationRequired), migration.UpdatedAt)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/testutil"
|
||||
)
|
||||
|
||||
func TestPostgresDesktopDiscoveryRootRoundTrip(t *testing.T) {
|
||||
db := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t))
|
||||
repo, err := NewWithDB(db, db, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("initialize postgres schema: %v", err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
migration := &models.DesktopDiscoveryMigration{HomeConfirmationRequired: true}
|
||||
if err := repo.SetDesktopDiscoveryMigration(ctx, migration); err != nil {
|
||||
t.Fatalf("set postgres migration: %v", err)
|
||||
}
|
||||
loadedMigration, err := repo.GetDesktopDiscoveryMigration(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("get postgres migration: %v", err)
|
||||
}
|
||||
if !loadedMigration.HomeConfirmationRequired {
|
||||
t.Fatal("postgres migration confirmation was not persisted")
|
||||
}
|
||||
|
||||
root := &models.DesktopDiscoveryRoot{
|
||||
ID: "postgres-discovery-root",
|
||||
Path: "/workspace/postgres-code",
|
||||
DisplayPath: "~/postgres-code",
|
||||
State: models.DesktopDiscoveryRootConnected,
|
||||
}
|
||||
if err := repo.CreateDesktopDiscoveryRoot(ctx, root); err != nil {
|
||||
t.Fatalf("create postgres discovery root: %v", err)
|
||||
}
|
||||
loaded, err := repo.GetDesktopDiscoveryRoot(ctx, root.Path)
|
||||
if err != nil {
|
||||
t.Fatalf("get postgres discovery root: %v", err)
|
||||
}
|
||||
if loaded == nil || loaded.ID != root.ID {
|
||||
t.Fatalf("loaded postgres root = %+v, want id %q", loaded, root.ID)
|
||||
}
|
||||
|
||||
loaded.State = models.DesktopDiscoveryRootReconnectRequired
|
||||
loaded.LastFailureCode = "permission_denied"
|
||||
if err := repo.UpdateDesktopDiscoveryRoot(ctx, loaded); err != nil {
|
||||
t.Fatalf("update postgres discovery root: %v", err)
|
||||
}
|
||||
listed, err := repo.ListDesktopDiscoveryRoots(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("list postgres discovery roots: %v", err)
|
||||
}
|
||||
if len(listed) != 1 || listed[0].State != models.DesktopDiscoveryRootReconnectRequired {
|
||||
t.Fatalf("listed postgres roots = %+v", listed)
|
||||
}
|
||||
|
||||
if err := repo.DeleteDesktopDiscoveryRoot(ctx, root.Path); err != nil {
|
||||
t.Fatalf("delete postgres discovery root: %v", err)
|
||||
}
|
||||
deleted, err := repo.GetDesktopDiscoveryRoot(ctx, root.Path)
|
||||
if err != nil {
|
||||
t.Fatalf("get deleted postgres discovery root: %v", err)
|
||||
}
|
||||
if deleted != nil {
|
||||
t.Fatalf("deleted postgres root still exists: %+v", deleted)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"github.com/kandev/kandev/internal/db"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
)
|
||||
|
||||
func newDesktopDiscoveryTestRepo(t *testing.T) (*Repository, *sqlx.DB) {
|
||||
t.Helper()
|
||||
dbConn, err := db.OpenSQLite(filepath.Join(t.TempDir(), "desktop-discovery.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
sqlxDB := sqlx.NewDb(dbConn, "sqlite3")
|
||||
repo, err := NewWithDB(sqlxDB, sqlxDB, nil)
|
||||
if err != nil {
|
||||
_ = sqlxDB.Close()
|
||||
t.Fatalf("new repository: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sqlxDB.Close() })
|
||||
return repo, sqlxDB
|
||||
}
|
||||
|
||||
func TestDesktopDiscoveryRootRoundTrip(t *testing.T) {
|
||||
repo, _ := newDesktopDiscoveryTestRepo(t)
|
||||
ctx := context.Background()
|
||||
|
||||
root := &models.DesktopDiscoveryRoot{
|
||||
ID: "root-1",
|
||||
Path: "/Users/example/Code",
|
||||
DisplayPath: "~/Code",
|
||||
State: models.DesktopDiscoveryRootConnected,
|
||||
}
|
||||
if err := repo.CreateDesktopDiscoveryRoot(ctx, root); err != nil {
|
||||
t.Fatalf("create root: %v", err)
|
||||
}
|
||||
if root.CreatedAt.IsZero() || root.UpdatedAt.IsZero() {
|
||||
t.Fatalf("create timestamps were not populated: %+v", root)
|
||||
}
|
||||
|
||||
got, err := repo.GetDesktopDiscoveryRoot(ctx, root.Path)
|
||||
if err != nil {
|
||||
t.Fatalf("get root: %v", err)
|
||||
}
|
||||
if got == nil || got.ID != root.ID || got.DisplayPath != root.DisplayPath {
|
||||
t.Fatalf("get root = %+v, want %+v", got, root)
|
||||
}
|
||||
|
||||
got.State = models.DesktopDiscoveryRootReconnectRequired
|
||||
got.LastFailureCode = "permission_denied"
|
||||
if err := repo.UpdateDesktopDiscoveryRoot(ctx, got); err != nil {
|
||||
t.Fatalf("update root: %v", err)
|
||||
}
|
||||
updated, err := repo.GetDesktopDiscoveryRoot(ctx, root.Path)
|
||||
if err != nil {
|
||||
t.Fatalf("get updated root: %v", err)
|
||||
}
|
||||
if updated.State != models.DesktopDiscoveryRootReconnectRequired || updated.LastFailureCode != "permission_denied" {
|
||||
t.Fatalf("updated root = %+v", updated)
|
||||
}
|
||||
|
||||
roots, err := repo.ListDesktopDiscoveryRoots(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("list roots: %v", err)
|
||||
}
|
||||
if len(roots) != 1 || roots[0].ID != root.ID {
|
||||
t.Fatalf("listed roots = %+v", roots)
|
||||
}
|
||||
if err := repo.DeleteDesktopDiscoveryRoot(ctx, root.Path); err != nil {
|
||||
t.Fatalf("delete root: %v", err)
|
||||
}
|
||||
deleted, err := repo.GetDesktopDiscoveryRoot(ctx, root.Path)
|
||||
if err != nil {
|
||||
t.Fatalf("get deleted root: %v", err)
|
||||
}
|
||||
if deleted != nil {
|
||||
t.Fatalf("deleted root still exists: %+v", deleted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDesktopDiscoveryMigrationRoundTripAndSchemaReplay(t *testing.T) {
|
||||
repo, sqlxDB := newDesktopDiscoveryTestRepo(t)
|
||||
ctx := context.Background()
|
||||
|
||||
migration, err := repo.GetDesktopDiscoveryMigration(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("get migration: %v", err)
|
||||
}
|
||||
if migration.HomeConfirmationRequired {
|
||||
t.Fatal("fresh installation unexpectedly requires Home confirmation")
|
||||
}
|
||||
|
||||
migration.HomeConfirmationRequired = true
|
||||
if err := repo.SetDesktopDiscoveryMigration(ctx, migration); err != nil {
|
||||
t.Fatalf("set migration: %v", err)
|
||||
}
|
||||
updated, err := repo.GetDesktopDiscoveryMigration(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("get updated migration: %v", err)
|
||||
}
|
||||
if !updated.HomeConfirmationRequired {
|
||||
t.Fatal("migration confirmation flag was not persisted")
|
||||
}
|
||||
|
||||
if _, err := NewWithDB(sqlxDB, sqlxDB, nil); err != nil {
|
||||
t.Fatalf("replay schema: %v", err)
|
||||
}
|
||||
replayed, err := repo.GetDesktopDiscoveryMigration(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("get replayed migration: %v", err)
|
||||
}
|
||||
if !replayed.HomeConfirmationRequired {
|
||||
t.Fatal("schema replay reset migration state")
|
||||
}
|
||||
}
|
||||
@@ -48,15 +48,18 @@ func (s *Service) ListDirectory(ctx context.Context, path string) (DirectoryList
|
||||
|
||||
abs, err := resolveListingPath(path)
|
||||
if err != nil {
|
||||
s.logFilesystemFailure("repository.discovery.directory_listing", path, "picker_opened", err)
|
||||
return DirectoryListing{}, err
|
||||
}
|
||||
|
||||
entries, err := readSubdirsBoundedAtFilesystemRoot(abs)
|
||||
if err != nil {
|
||||
s.logFilesystemFailure("repository.discovery.directory_listing", abs, "picker_opened", err)
|
||||
return DirectoryListing{}, err
|
||||
}
|
||||
|
||||
_ = ctx
|
||||
s.logFilesystemInfo("repository discovery directory listed", "repository.discovery.directory_listing", abs, "picker_opened")
|
||||
return DirectoryListing{
|
||||
Path: abs,
|
||||
Parent: parentPath(abs),
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package service
|
||||
|
||||
import "github.com/kandev/kandev/internal/common/fsdiagnostics"
|
||||
|
||||
func (s *Service) filesystemContext(operation, target, trigger string) fsdiagnostics.Context {
|
||||
return fsdiagnostics.Context{
|
||||
Operation: operation,
|
||||
Target: target,
|
||||
Trigger: trigger,
|
||||
Runtime: fsdiagnostics.RuntimeMode(s.discoveryConfig.DesktopRuntime),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) logFilesystemFailure(operation, target, trigger string, err error) {
|
||||
if s == nil || s.logger == nil || err == nil {
|
||||
return
|
||||
}
|
||||
operationContext := s.filesystemContext(operation, target, trigger)
|
||||
if fsdiagnostics.IsAccessDenied(err) {
|
||||
s.filesystemWarnings.Warn(s.logger.Zap(), "filesystem.access_denied", operationContext, err)
|
||||
return
|
||||
}
|
||||
s.logger.Warn("filesystem operation failed", operationContext.Fields(err)...)
|
||||
}
|
||||
|
||||
func (s *Service) logFilesystemInfo(message, operation, target, trigger string) {
|
||||
if s == nil || s.logger == nil {
|
||||
return
|
||||
}
|
||||
s.logger.Info(message, s.filesystemContext(operation, target, trigger).Fields(nil)...)
|
||||
}
|
||||
@@ -8,18 +8,23 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/common/fsdiagnostics"
|
||||
"github.com/kandev/kandev/internal/common/gitref"
|
||||
"github.com/kandev/kandev/internal/common/subproc"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
)
|
||||
|
||||
type RepositoryDiscoveryConfig struct {
|
||||
Roots []string
|
||||
MaxDepth int
|
||||
TaskWorktreeRoots []string
|
||||
DesktopRuntime bool
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -48,8 +53,15 @@ type Branch struct {
|
||||
}
|
||||
|
||||
type RepositoryDiscoveryResult struct {
|
||||
Roots []string
|
||||
Repositories []LocalRepository
|
||||
Roots []string
|
||||
Repositories []LocalRepository
|
||||
DesktopRuntime bool
|
||||
RootStates []models.DesktopDiscoveryRoot
|
||||
ScanTime *time.Time
|
||||
Refreshing bool
|
||||
Cached bool
|
||||
HomeConfirmationRequired bool
|
||||
FailedRoots []string
|
||||
}
|
||||
|
||||
type RepositoryPathValidation struct {
|
||||
@@ -77,48 +89,22 @@ const sourceTypeLocal = "local"
|
||||
const sourceTypeProvider = "provider"
|
||||
|
||||
func (s *Service) DiscoverLocalRepositories(ctx context.Context, root string) (RepositoryDiscoveryResult, error) {
|
||||
roots := s.discoveryRoots()
|
||||
if root != "" {
|
||||
absRoot, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return RepositoryDiscoveryResult{}, fmt.Errorf("invalid root path: %w", err)
|
||||
}
|
||||
if !isPathAllowed(absRoot, roots) {
|
||||
return RepositoryDiscoveryResult{}, ErrPathNotAllowed
|
||||
}
|
||||
roots = []string{absRoot}
|
||||
}
|
||||
return s.RefreshLocalRepositoryDiscovery(ctx, root)
|
||||
}
|
||||
|
||||
repos := make([]LocalRepository, 0)
|
||||
seen := make(map[string]struct{})
|
||||
for _, scanRoot := range roots {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return RepositoryDiscoveryResult{}, ctx.Err()
|
||||
default:
|
||||
}
|
||||
found, err := scanRootForRepos(ctx, scanRoot, s.discoveryMaxDepth())
|
||||
if err != nil {
|
||||
return RepositoryDiscoveryResult{}, err
|
||||
}
|
||||
for _, repo := range found {
|
||||
if _, ok := seen[repo.Path]; ok {
|
||||
continue
|
||||
}
|
||||
seen[repo.Path] = struct{}{}
|
||||
repos = append(repos, repo)
|
||||
}
|
||||
}
|
||||
|
||||
return RepositoryDiscoveryResult{
|
||||
Roots: roots,
|
||||
Repositories: repos,
|
||||
}, nil
|
||||
// DiscoverLocalRepositoriesForWorkspace applies the workspace visibility
|
||||
// check before using the legacy discovery endpoint.
|
||||
func (s *Service) DiscoverLocalRepositoriesForWorkspace(
|
||||
ctx context.Context,
|
||||
workspaceID, root string,
|
||||
) (RepositoryDiscoveryResult, error) {
|
||||
return s.refreshLocalRepositoryDiscovery(ctx, workspaceID, root, discoveryTriggerManualRefresh)
|
||||
}
|
||||
|
||||
func (s *Service) ValidateLocalRepositoryPath(ctx context.Context, path string) (RepositoryPathValidation, error) {
|
||||
absPath, err := filepath.Abs(filepath.Clean(path))
|
||||
if err != nil {
|
||||
s.logFilesystemFailure("repository.discovery.validation", path, "user_select", err)
|
||||
return RepositoryPathValidation{}, fmt.Errorf("invalid path: %w", err)
|
||||
}
|
||||
result := RepositoryPathValidation{Path: absPath, Allowed: true}
|
||||
@@ -134,6 +120,9 @@ func (s *Service) ValidateLocalRepositoryPath(ctx context.Context, path string)
|
||||
// codeql[go/path-injection] Intentional read-only diagnostics for the local path selected by the user.
|
||||
info, statErr := os.Stat(absPath)
|
||||
result.Exists = statErr == nil
|
||||
if statErr != nil && !errors.Is(statErr, os.ErrNotExist) {
|
||||
s.logFilesystemFailure("repository.discovery.validation", absPath, "user_select", statErr)
|
||||
}
|
||||
switch {
|
||||
case errors.Is(statErr, os.ErrNotExist):
|
||||
result.Message = "Path does not exist"
|
||||
@@ -718,8 +707,19 @@ func (s *Service) discoveryRoots() []string {
|
||||
var roots []string
|
||||
if len(s.discoveryConfig.Roots) > 0 {
|
||||
roots = append(roots, s.discoveryConfig.Roots...)
|
||||
} else if home, err := os.UserHomeDir(); err == nil {
|
||||
roots = append(roots, home)
|
||||
} else if !s.discoveryConfig.DesktopRuntime {
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
roots = append(roots, home)
|
||||
}
|
||||
}
|
||||
if s.discoveryConfig.DesktopRuntime && s.desktopRootStore != nil {
|
||||
if saved, err := s.desktopRootStore.ListDesktopDiscoveryRoots(context.Background()); err == nil {
|
||||
for _, root := range saved {
|
||||
if root != nil {
|
||||
roots = append(roots, root.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The orchestrator clones provider-backed repos into a configurable base
|
||||
// path. When that base path sits outside HOME (e.g. /data/repos in a
|
||||
@@ -764,12 +764,18 @@ func normalizeRoots(roots []string) []string {
|
||||
}
|
||||
|
||||
func scanRootForRepos(ctx context.Context, root string, maxDepth int) ([]LocalRepository, error) {
|
||||
if _, err := os.Stat(root); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
repos := make([]LocalRepository, 0)
|
||||
home, _ := os.UserHomeDir()
|
||||
walker := &repoWalker{
|
||||
root: root,
|
||||
maxDepth: maxDepth,
|
||||
libraryRoot: filepath.Join(root, "Library"),
|
||||
cacheRoot: filepath.Join(root, ".cache"),
|
||||
homeRoot: home,
|
||||
goos: runtime.GOOS,
|
||||
ctx: ctx,
|
||||
}
|
||||
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
|
||||
@@ -797,13 +803,18 @@ type repoWalker struct {
|
||||
maxDepth int
|
||||
libraryRoot string
|
||||
cacheRoot string
|
||||
homeRoot string
|
||||
goos string
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
// visit is the WalkDir callback. Returns a non-nil *LocalRepository when a git repo is found.
|
||||
func (w *repoWalker) visit(path string, d fs.DirEntry, err error) (*LocalRepository, error) {
|
||||
if err != nil {
|
||||
return nil, nil //nolint:nilerr // skip entries that cannot be accessed
|
||||
if path == w.root || fsdiagnostics.IsAccessDenied(err) {
|
||||
return nil, err
|
||||
}
|
||||
return nil, nil //nolint:nilerr // skip non-permission entries that cannot be accessed
|
||||
}
|
||||
if w.ctx.Err() != nil {
|
||||
return nil, w.ctx.Err()
|
||||
@@ -847,6 +858,9 @@ func (w *repoWalker) skipByName(path string, d fs.DirEntry) error {
|
||||
return nil
|
||||
}
|
||||
name := d.Name()
|
||||
if shouldSkipMacOSHomeChild(w.root, path, w.homeRoot, w.goos) {
|
||||
return fs.SkipDir
|
||||
}
|
||||
if (name == "Library" || name == ".cache") && filepath.Dir(path) == w.root {
|
||||
return fs.SkipDir
|
||||
}
|
||||
@@ -859,6 +873,19 @@ func (w *repoWalker) skipByName(path string, d fs.DirEntry) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func shouldSkipMacOSHomeChild(root, path, home, goos string) bool {
|
||||
if goos != "darwin" || home == "" || !sameCanonicalPath(root, home) {
|
||||
return false
|
||||
}
|
||||
if !sameCanonicalPath(filepath.Dir(path), root) {
|
||||
return false
|
||||
}
|
||||
name := filepath.Base(path)
|
||||
return strings.EqualFold(name, "Desktop") ||
|
||||
strings.EqualFold(name, "Documents") ||
|
||||
strings.EqualFold(name, "Downloads")
|
||||
}
|
||||
|
||||
// makeRepo builds a LocalRepository from a .git entry path.
|
||||
func (w *repoWalker) makeRepo(path string, d fs.DirEntry) *LocalRepository {
|
||||
repoPath := filepath.Dir(path)
|
||||
|
||||
@@ -0,0 +1,713 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/kandev/kandev/internal/common/fsdiagnostics"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
)
|
||||
|
||||
const discoveryRefreshAge = 30 * time.Minute
|
||||
|
||||
var (
|
||||
ErrDesktopDiscoveryUnavailable = errors.New("desktop discovery roots are unavailable")
|
||||
ErrInvalidDiscoveryRoot = errors.New("invalid discovery root")
|
||||
)
|
||||
|
||||
const (
|
||||
discoveryTriggerManualRefresh = "manual_refresh"
|
||||
discoveryTriggerStaleRefresh = "stale_refresh"
|
||||
discoveryTriggerUserSelect = "user_select"
|
||||
)
|
||||
|
||||
// NormalizeRepositoryDiscoveryTrigger keeps scan diagnostics within the
|
||||
// triggers understood by the discovery contract. Unknown or missing causes
|
||||
// are treated as an explicit manual refresh.
|
||||
func NormalizeRepositoryDiscoveryTrigger(trigger string) string {
|
||||
switch trigger {
|
||||
case discoveryTriggerManualRefresh, discoveryTriggerStaleRefresh, discoveryTriggerUserSelect:
|
||||
return trigger
|
||||
default:
|
||||
return discoveryTriggerManualRefresh
|
||||
}
|
||||
}
|
||||
|
||||
type discoveryCacheEntry struct {
|
||||
roots []string
|
||||
repositories []LocalRepository
|
||||
rootStates []models.DesktopDiscoveryRoot
|
||||
scanTime *time.Time
|
||||
failedRoots []string
|
||||
}
|
||||
|
||||
type discoveryFlight struct {
|
||||
done chan struct{}
|
||||
result RepositoryDiscoveryResult
|
||||
err error
|
||||
}
|
||||
|
||||
// DiscoveryRefreshAge is the freshness period used by the browser
|
||||
// coordinator. The backend exposes the scan timestamp and keeps the actual
|
||||
// scan operation explicit so callers can return cached choices immediately.
|
||||
func DiscoveryRefreshAge() time.Duration {
|
||||
return discoveryRefreshAge
|
||||
}
|
||||
|
||||
func (s *Service) ListDesktopDiscoveryRoots(ctx context.Context) ([]*models.DesktopDiscoveryRoot, error) {
|
||||
if !s.discoveryConfig.DesktopRuntime || s.desktopRootStore == nil {
|
||||
return nil, ErrDesktopDiscoveryUnavailable
|
||||
}
|
||||
return s.desktopRootStore.ListDesktopDiscoveryRoots(ctx)
|
||||
}
|
||||
|
||||
// GetLocalRepositoryDiscovery returns the current cached snapshot. It never
|
||||
// starts a filesystem walk. Call RefreshLocalRepositoryDiscovery for an
|
||||
// explicit or stale refresh.
|
||||
func (s *Service) GetLocalRepositoryDiscovery(ctx context.Context, root string) (RepositoryDiscoveryResult, error) {
|
||||
return s.getLocalRepositoryDiscovery(ctx, "", root)
|
||||
}
|
||||
|
||||
// GetLocalRepositoryDiscoveryForWorkspace applies the workspace visibility
|
||||
// check before returning a cached discovery snapshot.
|
||||
func (s *Service) GetLocalRepositoryDiscoveryForWorkspace(
|
||||
ctx context.Context,
|
||||
workspaceID, root string,
|
||||
) (RepositoryDiscoveryResult, error) {
|
||||
return s.getLocalRepositoryDiscovery(ctx, workspaceID, root)
|
||||
}
|
||||
|
||||
func (s *Service) getLocalRepositoryDiscovery(
|
||||
ctx context.Context,
|
||||
workspaceID, root string,
|
||||
) (RepositoryDiscoveryResult, error) {
|
||||
if err := s.authorizeWorkspaceID(ctx, workspaceID); err != nil {
|
||||
return RepositoryDiscoveryResult{}, err
|
||||
}
|
||||
roots, err := s.resolveDiscoveryRoots(ctx, root)
|
||||
if err != nil {
|
||||
return RepositoryDiscoveryResult{}, err
|
||||
}
|
||||
states, err := s.discoveryRootStates(ctx, roots)
|
||||
if err != nil {
|
||||
return RepositoryDiscoveryResult{}, err
|
||||
}
|
||||
homeConfirmation, err := s.homeConfirmationRequired(ctx)
|
||||
if err != nil {
|
||||
return RepositoryDiscoveryResult{}, err
|
||||
}
|
||||
key := discoveryCacheKey(roots, s.discoveryMaxDepth())
|
||||
|
||||
s.discoveryCacheMu.Lock()
|
||||
entry, cached := s.discoveryCache[key]
|
||||
refreshing := s.discoveryFlights[key] != nil
|
||||
s.discoveryCacheMu.Unlock()
|
||||
|
||||
if !cached {
|
||||
return RepositoryDiscoveryResult{
|
||||
Roots: roots,
|
||||
RootStates: states,
|
||||
DesktopRuntime: s.discoveryConfig.DesktopRuntime,
|
||||
Refreshing: refreshing,
|
||||
HomeConfirmationRequired: homeConfirmation,
|
||||
}, nil
|
||||
}
|
||||
if len(states) == 0 {
|
||||
states = cloneRootStates(entry.rootStates)
|
||||
}
|
||||
return RepositoryDiscoveryResult{
|
||||
Roots: roots,
|
||||
Repositories: cloneRepositories(entry.repositories),
|
||||
DesktopRuntime: s.discoveryConfig.DesktopRuntime,
|
||||
RootStates: states,
|
||||
ScanTime: cloneTime(entry.scanTime),
|
||||
Refreshing: refreshing,
|
||||
Cached: true,
|
||||
HomeConfirmationRequired: homeConfirmation,
|
||||
FailedRoots: append([]string(nil), entry.failedRoots...),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RefreshLocalRepositoryDiscovery performs one scan for the normalized root
|
||||
// set. Concurrent callers share the same in-flight scan. A failed root keeps
|
||||
// the previous successful repository list in the cache.
|
||||
func (s *Service) RefreshLocalRepositoryDiscovery(ctx context.Context, root string) (RepositoryDiscoveryResult, error) {
|
||||
return s.refreshLocalRepositoryDiscovery(ctx, "", root, discoveryTriggerManualRefresh)
|
||||
}
|
||||
|
||||
// RefreshLocalRepositoryDiscoveryForWorkspace applies the workspace
|
||||
// visibility check before starting or joining a discovery scan.
|
||||
func (s *Service) RefreshLocalRepositoryDiscoveryForWorkspace(
|
||||
ctx context.Context,
|
||||
workspaceID, root string,
|
||||
) (RepositoryDiscoveryResult, error) {
|
||||
return s.RefreshLocalRepositoryDiscoveryForWorkspaceWithTrigger(
|
||||
ctx, workspaceID, root, discoveryTriggerManualRefresh,
|
||||
)
|
||||
}
|
||||
|
||||
// RefreshLocalRepositoryDiscoveryForWorkspaceWithTrigger applies the
|
||||
// workspace visibility check before starting or joining a scan. The validated
|
||||
// trigger is retained in scan diagnostics so support can distinguish stale
|
||||
// activation from a user refresh or root selection.
|
||||
func (s *Service) RefreshLocalRepositoryDiscoveryForWorkspaceWithTrigger(
|
||||
ctx context.Context,
|
||||
workspaceID, root, trigger string,
|
||||
) (RepositoryDiscoveryResult, error) {
|
||||
return s.refreshLocalRepositoryDiscovery(
|
||||
ctx,
|
||||
workspaceID,
|
||||
root,
|
||||
NormalizeRepositoryDiscoveryTrigger(trigger),
|
||||
)
|
||||
}
|
||||
|
||||
func (s *Service) refreshLocalRepositoryDiscovery(
|
||||
ctx context.Context,
|
||||
workspaceID, root, trigger string,
|
||||
) (RepositoryDiscoveryResult, error) {
|
||||
trigger = NormalizeRepositoryDiscoveryTrigger(trigger)
|
||||
if err := s.authorizeWorkspaceID(ctx, workspaceID); err != nil {
|
||||
return RepositoryDiscoveryResult{}, err
|
||||
}
|
||||
roots, err := s.resolveDiscoveryRoots(ctx, root)
|
||||
if err != nil {
|
||||
return RepositoryDiscoveryResult{}, err
|
||||
}
|
||||
states, err := s.discoveryRootStates(ctx, roots)
|
||||
if err != nil {
|
||||
return RepositoryDiscoveryResult{}, err
|
||||
}
|
||||
homeConfirmation, err := s.homeConfirmationRequired(ctx)
|
||||
if err != nil {
|
||||
return RepositoryDiscoveryResult{}, err
|
||||
}
|
||||
if len(roots) == 0 {
|
||||
s.logFilesystemInfo("repository discovery scan skipped", "repository.discovery.scan", root, trigger)
|
||||
return RepositoryDiscoveryResult{
|
||||
Roots: roots,
|
||||
RootStates: states,
|
||||
DesktopRuntime: s.discoveryConfig.DesktopRuntime,
|
||||
HomeConfirmationRequired: homeConfirmation,
|
||||
}, nil
|
||||
}
|
||||
|
||||
key := discoveryCacheKey(roots, s.discoveryMaxDepth())
|
||||
s.discoveryCacheMu.Lock()
|
||||
if flight := s.discoveryFlights[key]; flight != nil {
|
||||
done := flight.done
|
||||
s.discoveryCacheMu.Unlock()
|
||||
select {
|
||||
case <-done:
|
||||
if errors.Is(flight.err, context.Canceled) || errors.Is(flight.err, context.DeadlineExceeded) {
|
||||
return s.refreshLocalRepositoryDiscovery(ctx, workspaceID, root, trigger)
|
||||
}
|
||||
return flight.result, flight.err
|
||||
case <-ctx.Done():
|
||||
return RepositoryDiscoveryResult{}, ctx.Err()
|
||||
}
|
||||
}
|
||||
previous, hasPrevious := s.discoveryCache[key]
|
||||
flight := &discoveryFlight{done: make(chan struct{})}
|
||||
s.discoveryFlights[key] = flight
|
||||
s.discoveryCacheMu.Unlock()
|
||||
|
||||
result, scanErr := s.scanDiscoveryRoots(ctx, roots, previous, hasPrevious, homeConfirmation, trigger)
|
||||
s.discoveryCacheMu.Lock()
|
||||
flight.result = result
|
||||
flight.err = scanErr
|
||||
delete(s.discoveryFlights, key)
|
||||
close(flight.done)
|
||||
s.discoveryCacheMu.Unlock()
|
||||
return result, scanErr
|
||||
}
|
||||
|
||||
func (s *Service) scanDiscoveryRoots(
|
||||
ctx context.Context,
|
||||
roots []string,
|
||||
previous discoveryCacheEntry,
|
||||
hasPrevious bool,
|
||||
homeConfirmation bool,
|
||||
trigger string,
|
||||
) (RepositoryDiscoveryResult, error) {
|
||||
trigger = NormalizeRepositoryDiscoveryTrigger(trigger)
|
||||
found := make([]LocalRepository, 0)
|
||||
failed := make([]string, 0)
|
||||
for _, root := range roots {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return RepositoryDiscoveryResult{}, err
|
||||
}
|
||||
s.logFilesystemInfo("repository discovery scan started", "repository.discovery.scan", root, trigger)
|
||||
repositories, err := s.discoveryScanRoot(ctx, root, s.discoveryMaxDepth())
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return RepositoryDiscoveryResult{}, err
|
||||
}
|
||||
failed = append(failed, root)
|
||||
s.logFilesystemFailure("repository.discovery.scan", root, trigger, err)
|
||||
s.recordDesktopRootFailure(ctx, root, err)
|
||||
continue
|
||||
}
|
||||
found = appendUniqueRepositories(found, repositories)
|
||||
s.recordDesktopRootSuccess(ctx, root)
|
||||
}
|
||||
|
||||
states, err := s.discoveryRootStates(ctx, roots)
|
||||
if err != nil {
|
||||
return RepositoryDiscoveryResult{}, err
|
||||
}
|
||||
if len(failed) > 0 {
|
||||
repositories := found
|
||||
scanTime := (*time.Time)(nil)
|
||||
cached := hasPrevious
|
||||
if hasPrevious {
|
||||
repositories = cloneRepositories(previous.repositories)
|
||||
scanTime = cloneTime(previous.scanTime)
|
||||
}
|
||||
entry := discoveryCacheEntry{
|
||||
roots: append([]string(nil), roots...),
|
||||
repositories: cloneRepositories(repositories),
|
||||
rootStates: cloneRootStates(states),
|
||||
scanTime: cloneTime(scanTime),
|
||||
failedRoots: append([]string(nil), failed...),
|
||||
}
|
||||
s.storeDiscoveryCache(roots, entry)
|
||||
return RepositoryDiscoveryResult{
|
||||
Roots: roots,
|
||||
Repositories: repositories,
|
||||
DesktopRuntime: s.discoveryConfig.DesktopRuntime,
|
||||
RootStates: states,
|
||||
ScanTime: scanTime,
|
||||
Cached: cached,
|
||||
HomeConfirmationRequired: homeConfirmation,
|
||||
FailedRoots: failed,
|
||||
}, nil
|
||||
}
|
||||
|
||||
now := s.discoveryClockNow()
|
||||
entry := discoveryCacheEntry{
|
||||
roots: append([]string(nil), roots...),
|
||||
repositories: cloneRepositories(found),
|
||||
rootStates: cloneRootStates(states),
|
||||
scanTime: &now,
|
||||
}
|
||||
s.storeDiscoveryCache(roots, entry)
|
||||
return RepositoryDiscoveryResult{
|
||||
Roots: roots,
|
||||
Repositories: found,
|
||||
DesktopRuntime: s.discoveryConfig.DesktopRuntime,
|
||||
RootStates: states,
|
||||
ScanTime: &now,
|
||||
HomeConfirmationRequired: homeConfirmation,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) storeDiscoveryCache(roots []string, entry discoveryCacheEntry) {
|
||||
key := discoveryCacheKey(roots, s.discoveryMaxDepth())
|
||||
s.discoveryCacheMu.Lock()
|
||||
s.discoveryCache[key] = entry
|
||||
s.discoveryCacheMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Service) resolveDiscoveryRoots(ctx context.Context, requestedRoot string) ([]string, error) {
|
||||
roots, err := s.effectiveDiscoveryRoots(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if requestedRoot == "" {
|
||||
return roots, nil
|
||||
}
|
||||
absRoot, err := filepath.Abs(filepath.Clean(requestedRoot))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid root path: %w", err)
|
||||
}
|
||||
if !isPathAllowed(absRoot, roots) {
|
||||
return nil, ErrPathNotAllowed
|
||||
}
|
||||
return []string{filepath.Clean(absRoot)}, nil
|
||||
}
|
||||
|
||||
func (s *Service) effectiveDiscoveryRoots(ctx context.Context) ([]string, error) {
|
||||
roots := make([]string, 0, len(s.discoveryConfig.Roots)+2)
|
||||
if len(s.discoveryConfig.Roots) > 0 {
|
||||
roots = append(roots, s.discoveryConfig.Roots...)
|
||||
} else if !s.discoveryConfig.DesktopRuntime {
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
roots = append(roots, home)
|
||||
}
|
||||
}
|
||||
if s.discoveryConfig.DesktopRuntime && s.desktopRootStore != nil {
|
||||
saved, err := s.desktopRootStore.ListDesktopDiscoveryRoots(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, root := range saved {
|
||||
if root != nil {
|
||||
roots = append(roots, root.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
if s.repoCloneLocation != nil {
|
||||
if base, err := s.repoCloneLocation.ExpandedBasePath(); err == nil && base != "" {
|
||||
roots = append(roots, base)
|
||||
}
|
||||
}
|
||||
return normalizeRoots(roots), nil
|
||||
}
|
||||
|
||||
func (s *Service) homeConfirmationRequired(ctx context.Context) (bool, error) {
|
||||
if !s.discoveryConfig.DesktopRuntime || s.desktopRootStore == nil || len(s.discoveryConfig.Roots) > 0 {
|
||||
return false, nil
|
||||
}
|
||||
roots, err := s.desktopRootStore.ListDesktopDiscoveryRoots(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if len(roots) > 0 {
|
||||
return false, nil
|
||||
}
|
||||
migration, err := s.desktopRootStore.GetDesktopDiscoveryMigration(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return migration != nil && migration.HomeConfirmationRequired, nil
|
||||
}
|
||||
|
||||
func (s *Service) discoveryRootStates(ctx context.Context, roots []string) ([]models.DesktopDiscoveryRoot, error) {
|
||||
stored := make(map[string]*models.DesktopDiscoveryRoot)
|
||||
if s.discoveryConfig.DesktopRuntime && s.desktopRootStore != nil {
|
||||
items, err := s.desktopRootStore.ListDesktopDiscoveryRoots(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, item := range items {
|
||||
if item != nil {
|
||||
stored[filepath.Clean(item.Path)] = item
|
||||
}
|
||||
}
|
||||
}
|
||||
states := make([]models.DesktopDiscoveryRoot, 0, len(roots))
|
||||
for _, root := range roots {
|
||||
if item := stored[filepath.Clean(root)]; item != nil {
|
||||
states = append(states, *cloneRoot(item))
|
||||
continue
|
||||
}
|
||||
states = append(states, models.DesktopDiscoveryRoot{
|
||||
Path: root,
|
||||
DisplayPath: displayDiscoveryPath(root),
|
||||
State: models.DesktopDiscoveryRootConnected,
|
||||
})
|
||||
}
|
||||
return states, nil
|
||||
}
|
||||
|
||||
// AddDesktopDiscoveryRoot persists a canonical install-wide root and starts
|
||||
// its first immediate scan. A scan failure is represented by root state so the
|
||||
// caller can offer recovery without treating an inaccessible folder as a
|
||||
// malformed request.
|
||||
func (s *Service) AddDesktopDiscoveryRoot(ctx context.Context, path string) (*models.DesktopDiscoveryRoot, error) {
|
||||
if !s.discoveryConfig.DesktopRuntime || s.desktopRootStore == nil {
|
||||
return nil, ErrDesktopDiscoveryUnavailable
|
||||
}
|
||||
canonical, err := canonicalDiscoveryRoot(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
root, err := s.desktopRootStore.GetDesktopDiscoveryRoot(ctx, canonical)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if root == nil {
|
||||
root = &models.DesktopDiscoveryRoot{
|
||||
ID: uuid.NewString(),
|
||||
Path: canonical,
|
||||
DisplayPath: displayDiscoveryPath(canonical),
|
||||
State: models.DesktopDiscoveryRootConnected,
|
||||
}
|
||||
if err := s.desktopRootStore.CreateDesktopDiscoveryRoot(ctx, root); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
root.State = models.DesktopDiscoveryRootConnected
|
||||
root.LastFailureAt = nil
|
||||
root.LastFailureCode = ""
|
||||
if err := s.desktopRootStore.UpdateDesktopDiscoveryRoot(ctx, root); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if isCurrentHomePath(canonical) {
|
||||
if err := s.clearHomeConfirmation(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
s.invalidateDiscoveryCache()
|
||||
if _, err := s.refreshLocalRepositoryDiscovery(ctx, "", "", discoveryTriggerUserSelect); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.getRequiredDesktopDiscoveryRoot(ctx, canonical)
|
||||
}
|
||||
|
||||
// ReconnectDesktopDiscoveryRoot replaces the path for an inaccessible root,
|
||||
// then performs one immediate scan under the new user-selected path.
|
||||
func (s *Service) ReconnectDesktopDiscoveryRoot(ctx context.Context, oldPath, newPath string) (*models.DesktopDiscoveryRoot, error) {
|
||||
if !s.discoveryConfig.DesktopRuntime || s.desktopRootStore == nil {
|
||||
return nil, ErrDesktopDiscoveryUnavailable
|
||||
}
|
||||
canonical, err := canonicalDiscoveryRoot(newPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
oldLookupPath, err := normalizeDiscoveryRootLookupPath(oldPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
old, err := s.desktopRootStore.GetDesktopDiscoveryRoot(ctx, oldLookupPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if old == nil {
|
||||
return s.AddDesktopDiscoveryRoot(ctx, canonical)
|
||||
}
|
||||
conflict, err := s.desktopRootStore.GetDesktopDiscoveryRoot(ctx, canonical)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if conflict != nil && conflict.ID != old.ID {
|
||||
return nil, fmt.Errorf("%w: root already exists", ErrInvalidDiscoveryRoot)
|
||||
}
|
||||
old.Path = canonical
|
||||
old.DisplayPath = displayDiscoveryPath(canonical)
|
||||
old.State = models.DesktopDiscoveryRootConnected
|
||||
old.LastScanAt = nil
|
||||
old.LastFailureAt = nil
|
||||
old.LastFailureCode = ""
|
||||
if err := s.desktopRootStore.UpdateDesktopDiscoveryRoot(ctx, old); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if isCurrentHomePath(canonical) {
|
||||
if err := s.clearHomeConfirmation(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
s.invalidateDiscoveryCache()
|
||||
if _, err := s.refreshLocalRepositoryDiscovery(ctx, "", "", discoveryTriggerUserSelect); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.getRequiredDesktopDiscoveryRoot(ctx, canonical)
|
||||
}
|
||||
|
||||
func (s *Service) getRequiredDesktopDiscoveryRoot(
|
||||
ctx context.Context, path string,
|
||||
) (*models.DesktopDiscoveryRoot, error) {
|
||||
root, err := s.desktopRootStore.GetDesktopDiscoveryRoot(ctx, path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if root == nil {
|
||||
return nil, errors.New("desktop discovery root disappeared after scan")
|
||||
}
|
||||
return root, nil
|
||||
}
|
||||
|
||||
func normalizeDiscoveryRootLookupPath(path string) (string, error) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return "", fmt.Errorf("%w: path is required", ErrInvalidDiscoveryRoot)
|
||||
}
|
||||
abs, err := filepath.Abs(filepath.Clean(path))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: %v", ErrInvalidDiscoveryRoot, err)
|
||||
}
|
||||
if canonical, err := filepath.EvalSymlinks(abs); err == nil {
|
||||
return filepath.Clean(canonical), nil
|
||||
}
|
||||
return filepath.Clean(abs), nil
|
||||
}
|
||||
|
||||
func (s *Service) RemoveDesktopDiscoveryRoot(ctx context.Context, path string) error {
|
||||
if !s.discoveryConfig.DesktopRuntime || s.desktopRootStore == nil {
|
||||
return ErrDesktopDiscoveryUnavailable
|
||||
}
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return fmt.Errorf("%w: path is required", ErrInvalidDiscoveryRoot)
|
||||
}
|
||||
canonical, err := filepath.Abs(filepath.Clean(path))
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrInvalidDiscoveryRoot, err)
|
||||
}
|
||||
if err := s.desktopRootStore.DeleteDesktopDiscoveryRoot(ctx, filepath.Clean(canonical)); err != nil {
|
||||
return err
|
||||
}
|
||||
s.invalidateDiscoveryCache()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) clearHomeConfirmation(ctx context.Context) error {
|
||||
return s.desktopRootStore.SetDesktopDiscoveryMigration(ctx, &models.DesktopDiscoveryMigration{})
|
||||
}
|
||||
|
||||
func (s *Service) recordDesktopRootSuccess(ctx context.Context, path string) {
|
||||
if !s.discoveryConfig.DesktopRuntime || s.desktopRootStore == nil {
|
||||
return
|
||||
}
|
||||
root, err := s.desktopRootStore.GetDesktopDiscoveryRoot(ctx, path)
|
||||
if err != nil || root == nil {
|
||||
return
|
||||
}
|
||||
now := s.discoveryClockNow()
|
||||
root.State = models.DesktopDiscoveryRootConnected
|
||||
root.LastScanAt = &now
|
||||
root.LastFailureAt = nil
|
||||
root.LastFailureCode = ""
|
||||
_ = s.desktopRootStore.UpdateDesktopDiscoveryRoot(ctx, root)
|
||||
}
|
||||
|
||||
func (s *Service) recordDesktopRootFailure(ctx context.Context, path string, scanErr error) {
|
||||
if !s.discoveryConfig.DesktopRuntime || s.desktopRootStore == nil {
|
||||
return
|
||||
}
|
||||
root, err := s.desktopRootStore.GetDesktopDiscoveryRoot(ctx, path)
|
||||
if err != nil || root == nil {
|
||||
return
|
||||
}
|
||||
now := s.discoveryClockNow()
|
||||
root.State = models.DesktopDiscoveryRootReconnectRequired
|
||||
root.LastFailureAt = &now
|
||||
root.LastFailureCode = discoveryFailureCode(scanErr)
|
||||
_ = s.desktopRootStore.UpdateDesktopDiscoveryRoot(ctx, root)
|
||||
}
|
||||
|
||||
func discoveryFailureCode(err error) string {
|
||||
switch {
|
||||
case fsdiagnostics.IsAccessDenied(err):
|
||||
return "permission_denied"
|
||||
case errors.Is(err, os.ErrNotExist):
|
||||
return "not_found"
|
||||
default:
|
||||
return "scan_failed"
|
||||
}
|
||||
}
|
||||
|
||||
func canonicalDiscoveryRoot(path string) (string, error) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return "", fmt.Errorf("%w: path is required", ErrInvalidDiscoveryRoot)
|
||||
}
|
||||
abs, err := filepath.Abs(filepath.Clean(path))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: %v", ErrInvalidDiscoveryRoot, err)
|
||||
}
|
||||
canonical, err := filepath.EvalSymlinks(abs)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: %v", ErrInvalidDiscoveryRoot, err)
|
||||
}
|
||||
info, err := os.Stat(canonical)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: %v", ErrInvalidDiscoveryRoot, err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return "", fmt.Errorf("%w: path is not a directory", ErrInvalidDiscoveryRoot)
|
||||
}
|
||||
return filepath.Clean(canonical), nil
|
||||
}
|
||||
|
||||
func displayDiscoveryPath(path string) string {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return path
|
||||
}
|
||||
rel, err := filepath.Rel(filepath.Clean(home), filepath.Clean(path))
|
||||
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
|
||||
return path
|
||||
}
|
||||
if rel == "." {
|
||||
return "~"
|
||||
}
|
||||
return filepath.Join("~", rel)
|
||||
}
|
||||
|
||||
func isCurrentHomePath(path string) bool {
|
||||
home, err := os.UserHomeDir()
|
||||
return err == nil && sameCanonicalPath(filepath.Clean(home), filepath.Clean(path))
|
||||
}
|
||||
|
||||
func (s *Service) invalidateDiscoveryCache() {
|
||||
s.discoveryCacheMu.Lock()
|
||||
s.discoveryCache = make(map[string]discoveryCacheEntry)
|
||||
s.discoveryCacheMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Service) discoveryClockNow() time.Time {
|
||||
if s.discoveryNow != nil {
|
||||
return s.discoveryNow().UTC()
|
||||
}
|
||||
return time.Now().UTC()
|
||||
}
|
||||
|
||||
func (s *Service) SetDiscoveryClockForTest(now func() time.Time) {
|
||||
s.discoveryNow = now
|
||||
}
|
||||
|
||||
func appendUniqueRepositories(dst []LocalRepository, src []LocalRepository) []LocalRepository {
|
||||
seen := make(map[string]struct{}, len(dst)+len(src))
|
||||
for _, repo := range dst {
|
||||
seen[repo.Path] = struct{}{}
|
||||
}
|
||||
for _, repo := range src {
|
||||
if _, ok := seen[repo.Path]; ok {
|
||||
continue
|
||||
}
|
||||
seen[repo.Path] = struct{}{}
|
||||
dst = append(dst, repo)
|
||||
}
|
||||
sort.Slice(dst, func(i, j int) bool { return dst[i].Path < dst[j].Path })
|
||||
return dst
|
||||
}
|
||||
|
||||
func discoveryCacheKey(roots []string, maxDepth int) string {
|
||||
ordered := append([]string(nil), roots...)
|
||||
sort.Strings(ordered)
|
||||
return fmt.Sprintf("%d:%s", maxDepth, strings.Join(ordered, "\x00"))
|
||||
}
|
||||
|
||||
func cloneRepositories(repositories []LocalRepository) []LocalRepository {
|
||||
return append([]LocalRepository(nil), repositories...)
|
||||
}
|
||||
|
||||
func cloneRootStates(states []models.DesktopDiscoveryRoot) []models.DesktopDiscoveryRoot {
|
||||
result := make([]models.DesktopDiscoveryRoot, 0, len(states))
|
||||
for i := range states {
|
||||
result = append(result, *cloneRoot(&states[i]))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func cloneRoot(root *models.DesktopDiscoveryRoot) *models.DesktopDiscoveryRoot {
|
||||
if root == nil {
|
||||
return nil
|
||||
}
|
||||
result := *root
|
||||
if root.LastScanAt != nil {
|
||||
value := *root.LastScanAt
|
||||
result.LastScanAt = &value
|
||||
}
|
||||
if root.LastFailureAt != nil {
|
||||
value := *root.LastFailureAt
|
||||
result.LastFailureAt = &value
|
||||
}
|
||||
return &result
|
||||
}
|
||||
|
||||
func cloneTime(value *time.Time) *time.Time {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
result := *value
|
||||
return &result
|
||||
}
|
||||
@@ -8,7 +8,9 @@ import (
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
@@ -16,6 +18,9 @@ import (
|
||||
"github.com/kandev/kandev/internal/events/bus"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/repository"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"go.uber.org/zap/zaptest/observer"
|
||||
)
|
||||
|
||||
func TestDiscoverLocalRepositoriesSkipsIgnoredRoots(t *testing.T) {
|
||||
@@ -55,6 +60,361 @@ func TestDiscoverLocalRepositoriesSkipsIgnoredRoots(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMacOSHomeDiscoverySkipsProtectedChildrenButScansExplicitRoot(t *testing.T) {
|
||||
home := filepath.Join(t.TempDir(), "home")
|
||||
for _, name := range []string{"Desktop", "Documents", "Downloads"} {
|
||||
if err := os.MkdirAll(filepath.Join(home, name), 0o755); err != nil {
|
||||
t.Fatalf("mkdir %s: %v", name, err)
|
||||
}
|
||||
if !shouldSkipMacOSHomeChild(home, filepath.Join(home, name), home, "darwin") {
|
||||
t.Fatalf("protected child %s was not skipped", name)
|
||||
}
|
||||
}
|
||||
if shouldSkipMacOSHomeChild(home, filepath.Join(home, "Code"), home, "darwin") {
|
||||
t.Fatal("ordinary Home child was skipped")
|
||||
}
|
||||
if shouldSkipMacOSHomeChild(
|
||||
filepath.Join(home, "Documents"),
|
||||
filepath.Join(home, "Documents", "project"),
|
||||
home,
|
||||
"darwin",
|
||||
) {
|
||||
t.Fatal("an explicitly selected protected root was skipped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDesktopDiscoveryWithoutRootDoesNotScanHome(t *testing.T) {
|
||||
home := filepath.Join(t.TempDir(), "home")
|
||||
if err := os.MkdirAll(home, 0o755); err != nil {
|
||||
t.Fatalf("create home: %v", err)
|
||||
}
|
||||
makeRepo(t, filepath.Join(home, "project"))
|
||||
t.Setenv("HOME", home)
|
||||
|
||||
svc := newDiscoveryService(t, home)
|
||||
svc.discoveryConfig = RepositoryDiscoveryConfig{DesktopRuntime: true, MaxDepth: 6}
|
||||
var scanCalls int
|
||||
svc.discoveryScanRoot = func(context.Context, string, int) ([]LocalRepository, error) {
|
||||
scanCalls++
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
result, err := svc.GetLocalRepositoryDiscovery(context.Background(), "")
|
||||
if err != nil {
|
||||
t.Fatalf("get desktop discovery snapshot: %v", err)
|
||||
}
|
||||
if len(result.Roots) != 0 || len(result.Repositories) != 0 {
|
||||
t.Fatalf("unconfigured desktop discovery returned filesystem data: %+v", result)
|
||||
}
|
||||
if _, err := svc.RefreshLocalRepositoryDiscovery(context.Background(), ""); err != nil {
|
||||
t.Fatalf("refresh unconfigured desktop discovery: %v", err)
|
||||
}
|
||||
if scanCalls != 0 {
|
||||
t.Fatalf("unconfigured desktop discovery scanned Home %d time(s)", scanCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepositoryDiscoveryScanUsesValidatedTrigger(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
trigger string
|
||||
want string
|
||||
}{
|
||||
{name: "manual", trigger: "manual_refresh", want: "manual_refresh"},
|
||||
{name: "stale", trigger: "stale_refresh", want: "stale_refresh"},
|
||||
{name: "user selection", trigger: "user_select", want: "user_select"},
|
||||
{name: "unknown", trigger: "not-a-trigger", want: "manual_refresh"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
svc := newDiscoveryService(t, root)
|
||||
core, logs := observer.New(zapcore.InfoLevel)
|
||||
observedLogger, err := logger.NewFromZap(zap.New(core))
|
||||
if err != nil {
|
||||
t.Fatalf("create observer logger: %v", err)
|
||||
}
|
||||
svc.logger = observedLogger
|
||||
svc.discoveryConfig = RepositoryDiscoveryConfig{Roots: []string{root}, MaxDepth: 6}
|
||||
svc.discoveryScanRoot = func(context.Context, string, int) ([]LocalRepository, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if _, err := svc.refreshLocalRepositoryDiscovery(
|
||||
context.Background(), "", "", test.trigger,
|
||||
); err != nil {
|
||||
t.Fatalf("refresh discovery: %v", err)
|
||||
}
|
||||
entries := logs.FilterMessage("repository discovery scan started").All()
|
||||
if len(entries) != 1 {
|
||||
t.Fatalf("scan-start log entries = %d, want 1", len(entries))
|
||||
}
|
||||
if got := entries[0].ContextMap()["trigger"]; got != test.want {
|
||||
t.Fatalf("scan trigger = %v, want %q", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDesktopDiscoveryRootPersistsAcrossServiceRestart(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
makeRepo(t, filepath.Join(root, "project"))
|
||||
svc, _, repo := createTestService(t)
|
||||
config := RepositoryDiscoveryConfig{DesktopRuntime: true, MaxDepth: 6}
|
||||
svc.discoveryConfig = config
|
||||
svc.desktopRootStore = repo
|
||||
|
||||
selected, err := svc.AddDesktopDiscoveryRoot(context.Background(), root)
|
||||
if err != nil {
|
||||
t.Fatalf("add desktop discovery root: %v", err)
|
||||
}
|
||||
if selected.Path != filepath.Clean(root) || selected.State != models.DesktopDiscoveryRootConnected {
|
||||
t.Fatalf("selected root = %+v", selected)
|
||||
}
|
||||
|
||||
restarted := NewService(Repos{DiscoveryRoots: repo}, NewMockEventBus(), svc.logger, config)
|
||||
roots, err := restarted.ListDesktopDiscoveryRoots(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("list roots after restart: %v", err)
|
||||
}
|
||||
if len(roots) != 1 || roots[0].Path != filepath.Clean(root) {
|
||||
t.Fatalf("persisted roots = %+v", roots)
|
||||
}
|
||||
result, err := restarted.RefreshLocalRepositoryDiscovery(context.Background(), "")
|
||||
if err != nil {
|
||||
t.Fatalf("refresh after restart: %v", err)
|
||||
}
|
||||
if len(result.Repositories) != 1 || result.Repositories[0].Path != filepath.Join(root, "project") {
|
||||
t.Fatalf("repositories after restart = %+v", result.Repositories)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDesktopDiscoveryRefreshSharesOneScan(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
svc := newDiscoveryService(t, root)
|
||||
svc.discoveryConfig = RepositoryDiscoveryConfig{Roots: []string{root}, MaxDepth: 6}
|
||||
started := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
var callsMu sync.Mutex
|
||||
calls := 0
|
||||
svc.discoveryScanRoot = func(context.Context, string, int) ([]LocalRepository, error) {
|
||||
callsMu.Lock()
|
||||
calls++
|
||||
callsMu.Unlock()
|
||||
close(started)
|
||||
<-release
|
||||
return []LocalRepository{{Path: filepath.Join(root, "project"), Name: "project"}}, nil
|
||||
}
|
||||
|
||||
results := make(chan RepositoryDiscoveryResult, 2)
|
||||
errs := make(chan error, 2)
|
||||
go func() {
|
||||
result, err := svc.RefreshLocalRepositoryDiscovery(context.Background(), "")
|
||||
results <- result
|
||||
errs <- err
|
||||
}()
|
||||
<-started
|
||||
secondReturned := make(chan struct{})
|
||||
go func() {
|
||||
result, err := svc.RefreshLocalRepositoryDiscovery(context.Background(), "")
|
||||
results <- result
|
||||
errs <- err
|
||||
close(secondReturned)
|
||||
}()
|
||||
select {
|
||||
case <-secondReturned:
|
||||
t.Fatal("second refresh completed before the shared scan was released")
|
||||
case <-time.After(10 * time.Millisecond):
|
||||
}
|
||||
close(release)
|
||||
for range 2 {
|
||||
if err := <-errs; err != nil {
|
||||
t.Fatalf("shared refresh error: %v", err)
|
||||
}
|
||||
result := <-results
|
||||
if len(result.Repositories) != 1 {
|
||||
t.Fatalf("shared refresh repositories = %+v", result.Repositories)
|
||||
}
|
||||
}
|
||||
callsMu.Lock()
|
||||
defer callsMu.Unlock()
|
||||
if calls != 1 {
|
||||
t.Fatalf("discovery scan calls = %d, want 1", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDesktopDiscoveryCancelledFlightDoesNotPoisonWaitingCaller(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
svc := newDiscoveryService(t, root)
|
||||
svc.discoveryConfig = RepositoryDiscoveryConfig{Roots: []string{root}, MaxDepth: 6}
|
||||
started := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
var callsMu sync.Mutex
|
||||
calls := 0
|
||||
svc.discoveryScanRoot = func(ctx context.Context, _ string, _ int) ([]LocalRepository, error) {
|
||||
callsMu.Lock()
|
||||
calls++
|
||||
callNumber := calls
|
||||
callsMu.Unlock()
|
||||
if callNumber == 1 {
|
||||
close(started)
|
||||
<-release
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return []LocalRepository{{Path: filepath.Join(root, "project"), Name: "project"}}, nil
|
||||
}
|
||||
|
||||
ownerCtx, cancelOwner := context.WithCancel(context.Background())
|
||||
ownerErr := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := svc.RefreshLocalRepositoryDiscovery(ownerCtx, "")
|
||||
ownerErr <- err
|
||||
}()
|
||||
<-started
|
||||
|
||||
waiterResult := make(chan RepositoryDiscoveryResult, 1)
|
||||
waiterErr := make(chan error, 1)
|
||||
go func() {
|
||||
result, err := svc.RefreshLocalRepositoryDiscovery(context.Background(), "")
|
||||
waiterResult <- result
|
||||
waiterErr <- err
|
||||
}()
|
||||
|
||||
cancelOwner()
|
||||
close(release)
|
||||
if err := <-ownerErr; !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("owner error = %v, want context canceled", err)
|
||||
}
|
||||
select {
|
||||
case err := <-waiterErr:
|
||||
if err != nil {
|
||||
t.Fatalf("waiting caller error = %v", err)
|
||||
}
|
||||
result := <-waiterResult
|
||||
if len(result.Repositories) != 1 {
|
||||
t.Fatalf("waiting caller repositories = %+v", result.Repositories)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("waiting caller did not retry the canceled flight")
|
||||
}
|
||||
|
||||
callsMu.Lock()
|
||||
defer callsMu.Unlock()
|
||||
if calls != 2 {
|
||||
t.Fatalf("discovery scan calls = %d, want 2", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepoWalkerPropagatesAccessDenied(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
walker := &repoWalker{root: root, ctx: context.Background()}
|
||||
|
||||
if _, err := walker.visit(root, nil, os.ErrPermission); !errors.Is(err, os.ErrPermission) {
|
||||
t.Fatalf("root access error = %v, want permission denied", err)
|
||||
}
|
||||
child := filepath.Join(root, "private")
|
||||
if _, err := walker.visit(child, nil, os.ErrPermission); !errors.Is(err, os.ErrPermission) {
|
||||
t.Fatalf("child access error = %v, want permission denied", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconnectDesktopDiscoveryRootNormalizesOldPath(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
svc.discoveryConfig = RepositoryDiscoveryConfig{DesktopRuntime: true, MaxDepth: 6}
|
||||
svc.desktopRootStore = repo
|
||||
oldRoot := t.TempDir()
|
||||
newRoot := t.TempDir()
|
||||
|
||||
selected, err := svc.AddDesktopDiscoveryRoot(context.Background(), oldRoot)
|
||||
if err != nil {
|
||||
t.Fatalf("add old discovery root: %v", err)
|
||||
}
|
||||
oldPath := oldRoot + string(os.PathSeparator)
|
||||
if alias := filepath.Join(t.TempDir(), "old-root"); os.Symlink(oldRoot, alias) == nil {
|
||||
oldPath = alias
|
||||
}
|
||||
|
||||
reconnected, err := svc.ReconnectDesktopDiscoveryRoot(context.Background(), oldPath, newRoot)
|
||||
if err != nil {
|
||||
t.Fatalf("reconnect discovery root: %v", err)
|
||||
}
|
||||
if reconnected.ID != selected.ID || reconnected.Path != filepath.Clean(newRoot) {
|
||||
t.Fatalf("reconnected root = %+v, want id %q and path %q", reconnected, selected.ID, newRoot)
|
||||
}
|
||||
roots, err := svc.ListDesktopDiscoveryRoots(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("list reconnected roots: %v", err)
|
||||
}
|
||||
if len(roots) != 1 || roots[0].Path != filepath.Clean(newRoot) {
|
||||
t.Fatalf("roots after reconnect = %+v", roots)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDesktopDiscoveryFailurePreservesCachedRepositories(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
repositoryPath := filepath.Join(root, "project")
|
||||
makeRepo(t, repositoryPath)
|
||||
svc := newDiscoveryService(t, root)
|
||||
svc.discoveryConfig = RepositoryDiscoveryConfig{DesktopRuntime: true, MaxDepth: 6}
|
||||
var fail bool
|
||||
svc.discoveryScanRoot = func(context.Context, string, int) ([]LocalRepository, error) {
|
||||
if fail {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
return []LocalRepository{{Path: repositoryPath, Name: "project"}}, nil
|
||||
}
|
||||
|
||||
if _, err := svc.AddDesktopDiscoveryRoot(context.Background(), root); err != nil {
|
||||
t.Fatalf("seed desktop discovery cache: %v", err)
|
||||
}
|
||||
fail = true
|
||||
result, err := svc.RefreshLocalRepositoryDiscovery(context.Background(), "")
|
||||
if err != nil {
|
||||
t.Fatalf("partial discovery refresh: %v", err)
|
||||
}
|
||||
if len(result.Repositories) != 1 || result.Repositories[0].Path != repositoryPath {
|
||||
t.Fatalf("cached repositories were not preserved: %+v", result.Repositories)
|
||||
}
|
||||
if len(result.FailedRoots) != 1 || result.FailedRoots[0] != root {
|
||||
t.Fatalf("failed roots = %+v", result.FailedRoots)
|
||||
}
|
||||
roots, err := svc.ListDesktopDiscoveryRoots(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("list failed root: %v", err)
|
||||
}
|
||||
if roots[0].State != models.DesktopDiscoveryRootReconnectRequired || roots[0].LastFailureCode != "permission_denied" {
|
||||
t.Fatalf("failed root state = %+v", roots[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDesktopDiscoveryMigrationCanRequireHomeConfirmation(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
if err := repo.SetDesktopDiscoveryMigration(context.Background(), &models.DesktopDiscoveryMigration{
|
||||
HomeConfirmationRequired: true,
|
||||
}); err != nil {
|
||||
t.Fatalf("set migration state: %v", err)
|
||||
}
|
||||
svc.discoveryConfig = RepositoryDiscoveryConfig{DesktopRuntime: true}
|
||||
svc.desktopRootStore = repo
|
||||
|
||||
result, err := svc.GetLocalRepositoryDiscovery(context.Background(), "")
|
||||
if err != nil {
|
||||
t.Fatalf("get migration snapshot: %v", err)
|
||||
}
|
||||
if !result.HomeConfirmationRequired || len(result.Roots) != 0 {
|
||||
t.Fatalf("migration snapshot = %+v", result)
|
||||
}
|
||||
if _, err := svc.AddDesktopDiscoveryRoot(context.Background(), t.TempDir()); err != nil {
|
||||
t.Fatalf("select root while migration is pending: %v", err)
|
||||
}
|
||||
result, err = svc.GetLocalRepositoryDiscovery(context.Background(), "")
|
||||
if err != nil {
|
||||
t.Fatalf("get cleared migration snapshot: %v", err)
|
||||
}
|
||||
if result.HomeConfirmationRequired {
|
||||
t.Fatal("root selection did not clear Home confirmation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateLocalRepositoryPath(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
svc := newDiscoveryService(t, root)
|
||||
@@ -668,18 +1028,19 @@ func newDiscoveryService(t *testing.T, root string) *Service {
|
||||
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json", OutputPath: "stdout"})
|
||||
eventBus := bus.NewMemoryEventBus(log)
|
||||
return NewService(Repos{
|
||||
Workspaces: repo,
|
||||
Tasks: repo,
|
||||
TaskRepos: repo,
|
||||
Workflows: repo,
|
||||
Messages: repo,
|
||||
Turns: repo,
|
||||
Sessions: repo,
|
||||
GitSnapshots: repo,
|
||||
RepoEntities: repo,
|
||||
Executors: repo,
|
||||
Environments: repo,
|
||||
Reviews: repo,
|
||||
Workspaces: repo,
|
||||
Tasks: repo,
|
||||
TaskRepos: repo,
|
||||
Workflows: repo,
|
||||
Messages: repo,
|
||||
Turns: repo,
|
||||
Sessions: repo,
|
||||
GitSnapshots: repo,
|
||||
RepoEntities: repo,
|
||||
DiscoveryRoots: repo,
|
||||
Executors: repo,
|
||||
Environments: repo,
|
||||
Reviews: repo,
|
||||
}, eventBus, log, RepositoryDiscoveryConfig{
|
||||
Roots: []string{root},
|
||||
MaxDepth: 6,
|
||||
|
||||
@@ -7,9 +7,11 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"github.com/kandev/kandev/internal/common/fsdiagnostics"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/events/bus"
|
||||
"github.com/kandev/kandev/internal/secrets"
|
||||
@@ -312,6 +314,7 @@ type Repos struct {
|
||||
Sessions repository.SessionRepository
|
||||
GitSnapshots repository.GitSnapshotRepository
|
||||
RepoEntities repository.RepositoryEntityRepository
|
||||
DiscoveryRoots repository.DesktopDiscoveryRootRepository
|
||||
RepositorySets repository.RepositorySetRepository
|
||||
BranchPolicies repository.RepositoryBranchPolicyRepository
|
||||
RepositoryCleanup repository.RepositoryCleanupRepository
|
||||
@@ -343,6 +346,7 @@ type Service struct {
|
||||
sessions repository.SessionRepository
|
||||
gitSnapshots repository.GitSnapshotRepository
|
||||
repoEntities repository.RepositoryEntityRepository
|
||||
desktopRootStore repository.DesktopDiscoveryRootRepository
|
||||
repositorySets repository.RepositorySetRepository
|
||||
branchPolicies repository.RepositoryBranchPolicyRepository
|
||||
repositoryCleanup repository.RepositoryCleanupRepository
|
||||
@@ -363,6 +367,12 @@ type Service struct {
|
||||
eventBus bus.EventBus
|
||||
logger *logger.Logger
|
||||
discoveryConfig RepositoryDiscoveryConfig
|
||||
discoveryCacheMu sync.Mutex
|
||||
discoveryCache map[string]discoveryCacheEntry
|
||||
discoveryFlights map[string]*discoveryFlight
|
||||
discoveryNow func() time.Time
|
||||
discoveryScanRoot func(context.Context, string, int) ([]LocalRepository, error)
|
||||
filesystemWarnings *fsdiagnostics.WarningLimiter
|
||||
worktreeCleanup WorktreeCleanup
|
||||
canvasCleanup CanvasCleanup
|
||||
executionStopper TaskExecutionStopper
|
||||
@@ -509,6 +519,7 @@ func NewService(repos Repos, eventBus bus.EventBus, log *logger.Logger, discover
|
||||
sessions: repos.Sessions,
|
||||
gitSnapshots: repos.GitSnapshots,
|
||||
repoEntities: repos.RepoEntities,
|
||||
desktopRootStore: repos.DiscoveryRoots,
|
||||
repositorySets: repos.RepositorySets,
|
||||
branchPolicies: repos.BranchPolicies,
|
||||
repositoryCleanup: repos.RepositoryCleanup,
|
||||
@@ -524,6 +535,11 @@ func NewService(repos Repos, eventBus bus.EventBus, log *logger.Logger, discover
|
||||
eventBus: eventBus,
|
||||
logger: log,
|
||||
discoveryConfig: discoveryConfig,
|
||||
discoveryCache: make(map[string]discoveryCacheEntry),
|
||||
discoveryFlights: make(map[string]*discoveryFlight),
|
||||
discoveryNow: time.Now,
|
||||
discoveryScanRoot: scanRootForRepos,
|
||||
filesystemWarnings: fsdiagnostics.NewWarningLimiter(0),
|
||||
branchFetcher: newBranchFetcher(log.Zap()),
|
||||
lastTaskActivity: make(map[string]v1.ForegroundActivity),
|
||||
lastTaskSubagentCount: make(map[string]int),
|
||||
|
||||
@@ -113,6 +113,19 @@ func TestWorkspaceScopingListAndGet(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspaceScopingDiscoveryRejectsForeignWorkspace(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
seedScopedWorkspaces(t, repo)
|
||||
svc.discoveryConfig = RepositoryDiscoveryConfig{Roots: []string{t.TempDir()}, MaxDepth: 2}
|
||||
|
||||
if _, err := svc.GetLocalRepositoryDiscoveryForWorkspace(ctxAs("user-a"), "ws-b", ""); !errors.Is(err, repoerrors.ErrWorkspaceNotFound) {
|
||||
t.Fatalf("get foreign discovery snapshot: %v", err)
|
||||
}
|
||||
if _, err := svc.RefreshLocalRepositoryDiscoveryForWorkspace(ctxAs("user-a"), "ws-b", ""); !errors.Is(err, repoerrors.ErrWorkspaceNotFound) {
|
||||
t.Fatalf("refresh foreign discovery snapshot: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspaceScopingMutations(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
seedScopedWorkspaces(t, repo)
|
||||
|
||||
@@ -59,6 +59,15 @@ type RuntimeConfig struct {
|
||||
// same "<prefix> Kandev" for the
|
||||
// /api/v1/app-state boot path, which never renders through the shell.
|
||||
TitlePrefix string `json:"titlePrefix,omitempty"`
|
||||
// NativeFolderPickerAvailable is true only when the desktop shell launched
|
||||
// this backend and can service the narrow native folder-picker command.
|
||||
// Browsers must continue to use the HTTP directory picker.
|
||||
NativeFolderPickerAvailable bool `json:"nativeFolderPickerAvailable,omitempty"`
|
||||
// DesktopRuntime identifies the launch policy selected by the backend
|
||||
// process marker. It is separate from the native picker capability so an
|
||||
// ordinary browser connected to a desktop backend keeps desktop discovery
|
||||
// policy while using the HTTP picker.
|
||||
DesktopRuntime bool `json:"desktopRuntime,omitempty"`
|
||||
}
|
||||
|
||||
// BootError is a serializable non-fatal boot-data error for partial hydration.
|
||||
|
||||
@@ -590,6 +590,13 @@ func requestBranchIdentitySlug(req CreateRequest) string {
|
||||
return SanitizeBranchSlug(req.BranchSlug)
|
||||
}
|
||||
|
||||
func recreateSourceBranch(existingBranch, checkoutBranch string) string {
|
||||
if checkoutBranch != "" {
|
||||
return checkoutBranch
|
||||
}
|
||||
return existingBranch
|
||||
}
|
||||
|
||||
// resolveBaseRefWithFallback resolves the base ref for a new worktree, optionally
|
||||
// pulling from origin first, and falling back to req.FallbackBaseBranch when the
|
||||
// requested base branch is missing. When the fallback path is taken, req.BaseBranch
|
||||
@@ -1951,23 +1958,22 @@ func (m *Manager) recreate(ctx context.Context, existing *Worktree, req CreateRe
|
||||
}
|
||||
refreshedStartPoint := ""
|
||||
if req.RemoteSyncHandled && req.RemoteContribution == nil && emptyRemoteBaseRef == "" {
|
||||
sourceBranch := existing.Branch
|
||||
if req.CheckoutBranch != "" {
|
||||
sourceBranch = req.CheckoutBranch
|
||||
}
|
||||
sourceBranch := recreateSourceBranch(existing.Branch, req.CheckoutBranch)
|
||||
selectedRef, prepareErr := m.prepareBranchFromRefreshedOrigin(
|
||||
ctx, req.RepositoryPath, existing.Branch, sourceBranch, req.PRNumber,
|
||||
)
|
||||
if prepareErr != nil {
|
||||
return nil, prepareErr
|
||||
}
|
||||
if selectedRef == "" {
|
||||
if selectedRef == "" && !req.AllowBranchReplacement {
|
||||
err := &BranchUnrecoverableError{Branch: sourceBranch}
|
||||
if req.AllowBranchReplacement {
|
||||
return m.replaceUnrecoverableWorktree(ctx, existing, req, err)
|
||||
}
|
||||
return nil, fmt.Errorf("%w: refreshed branch %q was not materialized", err, sourceBranch)
|
||||
}
|
||||
if selectedRef == "" {
|
||||
return m.replaceUnrecoverableWorktree(
|
||||
ctx, existing, req, &BranchUnrecoverableError{Branch: sourceBranch},
|
||||
)
|
||||
}
|
||||
if selectedRef != existing.Branch {
|
||||
refreshedStartPoint = selectedRef
|
||||
}
|
||||
|
||||
Generated
+77
-10
@@ -774,7 +774,7 @@ dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -949,7 +949,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1856,6 +1856,7 @@ dependencies = [
|
||||
"serde_with",
|
||||
"tauri",
|
||||
"tauri-build",
|
||||
"tauri-plugin-dialog",
|
||||
"tauri-plugin-notification",
|
||||
"tauri-plugin-opener",
|
||||
"tauri-plugin-single-instance",
|
||||
@@ -2045,7 +2046,7 @@ dependencies = [
|
||||
"png 0.18.1",
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2835,6 +2836,30 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rfd"
|
||||
version = "0.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672"
|
||||
dependencies = [
|
||||
"block2",
|
||||
"dispatch2",
|
||||
"glib-sys",
|
||||
"gobject-sys",
|
||||
"gtk-sys",
|
||||
"js-sys",
|
||||
"log",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation",
|
||||
"raw-window-handle",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
@@ -2874,7 +2899,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2930,7 +2955,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3315,7 +3340,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3659,6 +3684,48 @@ dependencies = [
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-dialog"
|
||||
version = "2.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2d3c1dbe38037e7f590cdf2492594d5ceebe031e7bc7e827509b22a999d2940"
|
||||
dependencies = [
|
||||
"log",
|
||||
"raw-window-handle",
|
||||
"rfd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"tauri-plugin",
|
||||
"tauri-plugin-fs",
|
||||
"thiserror 2.0.18",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-fs"
|
||||
version = "2.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7ecc274121aca0c036a2b42d1cbe83d368d348f54e0bb8a735c2b1548e8f371"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"dunce",
|
||||
"glob",
|
||||
"log",
|
||||
"objc2-foundation",
|
||||
"percent-encoding",
|
||||
"schemars 0.8.22",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_repr",
|
||||
"tauri",
|
||||
"tauri-plugin",
|
||||
"tauri-utils",
|
||||
"thiserror 2.0.18",
|
||||
"toml 1.1.2+spec-1.1.0",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-notification"
|
||||
version = "2.3.3"
|
||||
@@ -3870,7 +3937,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4220,7 +4287,7 @@ dependencies = [
|
||||
"png 0.18.1",
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4249,7 +4316,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
|
||||
dependencies = [
|
||||
"memoffset",
|
||||
"tempfile",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4627,7 +4694,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -25,6 +25,7 @@ desktop-runtime = [
|
||||
"dep:tauri-plugin-opener",
|
||||
"dep:tauri-plugin-updater",
|
||||
"dep:tauri-plugin-notification",
|
||||
"dep:tauri-plugin-dialog",
|
||||
"dep:tauri-plugin-single-instance",
|
||||
"dep:tauri-runtime",
|
||||
]
|
||||
@@ -49,4 +50,5 @@ tauri-plugin-single-instance = { version = "=2.4.3", optional = true }
|
||||
tauri-plugin-updater = { version = "=2.10.1", optional = true }
|
||||
tauri-plugin-notification = { version = "=2.3.3", optional = true }
|
||||
tauri-plugin-opener = { version = "=2.5.4", optional = true }
|
||||
tauri-plugin-dialog = { version = "=2.7.2", optional = true }
|
||||
url = "2"
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSDesktopFolderUsageDescription</key>
|
||||
<string>Kandev needs access to folders you choose to discover local repositories.</string>
|
||||
<key>NSDocumentsFolderUsageDescription</key>
|
||||
<string>Kandev needs access to folders you choose to discover local repositories.</string>
|
||||
<key>NSDownloadsFolderUsageDescription</key>
|
||||
<string>Kandev needs access to folders you choose to discover local repositories.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -8,6 +8,7 @@ fn main() {
|
||||
"get_native_notification_permission",
|
||||
"request_native_notification_permission",
|
||||
"open_external_url",
|
||||
"pick_directory",
|
||||
]);
|
||||
tauri_build::try_build(tauri_build::Attributes::new().app_manifest(manifest))
|
||||
.expect("failed to build Tauri desktop application");
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"allow-show-native-notification",
|
||||
"allow-get-native-notification-permission",
|
||||
"allow-request-native-notification-permission",
|
||||
"allow-open-external-url"
|
||||
"allow-open-external-url",
|
||||
"allow-pick-directory"
|
||||
]
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1 +1 @@
|
||||
{"default":{"identifier":"default","description":"Desktop bridge; privileged commands verify the exact owned backend origin","remote":{"urls":["http://127.0.0.1:*"]},"local":false,"windows":["main"],"permissions":["core:event:allow-listen","core:event:allow-unlisten","allow-get-update-state","allow-check-for-updates","allow-install-update","allow-show-native-notification","allow-get-native-notification-permission","allow-request-native-notification-permission","allow-open-external-url"]}}
|
||||
{"default":{"identifier":"default","description":"Desktop bridge; privileged commands verify the exact owned backend origin","remote":{"urls":["http://127.0.0.1:*"]},"local":false,"windows":["main"],"permissions":["core:event:allow-listen","core:event:allow-unlisten","allow-get-update-state","allow-check-for-updates","allow-install-update","allow-show-native-notification","allow-get-native-notification-permission","allow-request-native-notification-permission","allow-open-external-url","allow-pick-directory"]}}
|
||||
@@ -374,6 +374,12 @@
|
||||
"const": "allow-open-external-url",
|
||||
"markdownDescription": "Enables the open_external_url command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the pick_directory command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-pick-directory",
|
||||
"markdownDescription": "Enables the pick_directory command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the request_native_notification_permission command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
@@ -416,6 +422,12 @@
|
||||
"const": "deny-open-external-url",
|
||||
"markdownDescription": "Denies the open_external_url command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the pick_directory command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-pick-directory",
|
||||
"markdownDescription": "Denies the pick_directory command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the request_native_notification_permission command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
@@ -2444,6 +2456,72 @@
|
||||
"const": "core:window:deny-unminimize",
|
||||
"markdownDescription": "Denies the unminimize command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n\n#### This default permission set includes:\n\n- `allow-message`\n- `allow-save`\n- `allow-open`",
|
||||
"type": "string",
|
||||
"const": "dialog:default",
|
||||
"markdownDescription": "This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n\n#### This default permission set includes:\n\n- `allow-message`\n- `allow-save`\n- `allow-open`"
|
||||
},
|
||||
{
|
||||
"description": "Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)",
|
||||
"type": "string",
|
||||
"const": "dialog:allow-ask",
|
||||
"markdownDescription": "Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)"
|
||||
},
|
||||
{
|
||||
"description": "Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)",
|
||||
"type": "string",
|
||||
"const": "dialog:allow-confirm",
|
||||
"markdownDescription": "Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)"
|
||||
},
|
||||
{
|
||||
"description": "Enables the message command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "dialog:allow-message",
|
||||
"markdownDescription": "Enables the message command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the open command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "dialog:allow-open",
|
||||
"markdownDescription": "Enables the open command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the save command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "dialog:allow-save",
|
||||
"markdownDescription": "Enables the save command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)",
|
||||
"type": "string",
|
||||
"const": "dialog:deny-ask",
|
||||
"markdownDescription": "Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)"
|
||||
},
|
||||
{
|
||||
"description": "Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)",
|
||||
"type": "string",
|
||||
"const": "dialog:deny-confirm",
|
||||
"markdownDescription": "Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)"
|
||||
},
|
||||
{
|
||||
"description": "Denies the message command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "dialog:deny-message",
|
||||
"markdownDescription": "Denies the message command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the open command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "dialog:deny-open",
|
||||
"markdownDescription": "Denies the open command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the save command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "dialog:deny-save",
|
||||
"markdownDescription": "Denies the save command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n\n#### This default permission set includes:\n\n- `allow-is-permission-granted`\n- `allow-request-permission`\n- `allow-notify`\n- `allow-register-action-types`\n- `allow-register-listener`\n- `allow-cancel`\n- `allow-get-pending`\n- `allow-remove-active`\n- `allow-get-active`\n- `allow-check-permissions`\n- `allow-show`\n- `allow-batch`\n- `allow-list-channels`\n- `allow-delete-channel`\n- `allow-create-channel`\n- `allow-permission-state`",
|
||||
"type": "string",
|
||||
|
||||
@@ -374,6 +374,12 @@
|
||||
"const": "allow-open-external-url",
|
||||
"markdownDescription": "Enables the open_external_url command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the pick_directory command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-pick-directory",
|
||||
"markdownDescription": "Enables the pick_directory command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the request_native_notification_permission command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
@@ -416,6 +422,12 @@
|
||||
"const": "deny-open-external-url",
|
||||
"markdownDescription": "Denies the open_external_url command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the pick_directory command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-pick-directory",
|
||||
"markdownDescription": "Denies the pick_directory command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the request_native_notification_permission command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
@@ -2444,6 +2456,72 @@
|
||||
"const": "core:window:deny-unminimize",
|
||||
"markdownDescription": "Denies the unminimize command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n\n#### This default permission set includes:\n\n- `allow-message`\n- `allow-save`\n- `allow-open`",
|
||||
"type": "string",
|
||||
"const": "dialog:default",
|
||||
"markdownDescription": "This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n\n#### This default permission set includes:\n\n- `allow-message`\n- `allow-save`\n- `allow-open`"
|
||||
},
|
||||
{
|
||||
"description": "Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)",
|
||||
"type": "string",
|
||||
"const": "dialog:allow-ask",
|
||||
"markdownDescription": "Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)"
|
||||
},
|
||||
{
|
||||
"description": "Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)",
|
||||
"type": "string",
|
||||
"const": "dialog:allow-confirm",
|
||||
"markdownDescription": "Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)"
|
||||
},
|
||||
{
|
||||
"description": "Enables the message command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "dialog:allow-message",
|
||||
"markdownDescription": "Enables the message command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the open command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "dialog:allow-open",
|
||||
"markdownDescription": "Enables the open command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the save command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "dialog:allow-save",
|
||||
"markdownDescription": "Enables the save command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)",
|
||||
"type": "string",
|
||||
"const": "dialog:deny-ask",
|
||||
"markdownDescription": "Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)"
|
||||
},
|
||||
{
|
||||
"description": "Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)",
|
||||
"type": "string",
|
||||
"const": "dialog:deny-confirm",
|
||||
"markdownDescription": "Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)"
|
||||
},
|
||||
{
|
||||
"description": "Denies the message command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "dialog:deny-message",
|
||||
"markdownDescription": "Denies the message command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the open command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "dialog:deny-open",
|
||||
"markdownDescription": "Denies the open command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the save command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "dialog:deny-save",
|
||||
"markdownDescription": "Denies the save command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n\n#### This default permission set includes:\n\n- `allow-is-permission-granted`\n- `allow-request-permission`\n- `allow-notify`\n- `allow-register-action-types`\n- `allow-register-listener`\n- `allow-cancel`\n- `allow-get-pending`\n- `allow-remove-active`\n- `allow-get-active`\n- `allow-check-permissions`\n- `allow-show`\n- `allow-batch`\n- `allow-list-channels`\n- `allow-delete-channel`\n- `allow-create-channel`\n- `allow-permission-state`",
|
||||
"type": "string",
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
[[permission]]
|
||||
identifier = "allow-pick-directory"
|
||||
description = "Enables the Kandev-owned directory picker command without exposing generic dialog commands."
|
||||
commands.allow = ["pick_directory"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-pick-directory"
|
||||
description = "Denies the Kandev-owned directory picker command."
|
||||
commands.deny = ["pick_directory"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-pick-directory"
|
||||
description = "Enables the pick_directory command without any pre-configured scope."
|
||||
commands.allow = ["pick_directory"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-pick-directory"
|
||||
description = "Denies the pick_directory command without any pre-configured scope."
|
||||
commands.deny = ["pick_directory"]
|
||||
@@ -24,6 +24,7 @@ const DEFAULT_DESKTOP_PORT: u16 = 38430;
|
||||
const DESKTOP_PORT_ENV: &str = "KANDEV_DESKTOP_PORT";
|
||||
const DESKTOP_HEALTH_TOKEN_ENV: &str = "KANDEV_DESKTOP_HEALTH_TOKEN";
|
||||
const DESKTOP_NATIVE_NOTIFICATIONS_ENV: &str = "KANDEV_DESKTOP_NATIVE_NOTIFICATIONS";
|
||||
const DESKTOP_RUNTIME_ENV: &str = "KANDEV_DESKTOP_RUNTIME";
|
||||
const LAUNCHER_PARENT_PID_ENV: &str = "KANDEV_LAUNCHER_PARENT_PID";
|
||||
const DESKTOP_HEALTH_TOKEN_HEADER: &str = "x-kandev-desktop-health-token";
|
||||
const STARTUP_OUTPUT_LIMIT: usize = 12 * 1024;
|
||||
@@ -369,8 +370,9 @@ pub fn desktop_environment(
|
||||
) -> BTreeMap<OsString, OsString> {
|
||||
let path = normalized_path(env.get(OsStr::new("PATH")), home_dir);
|
||||
env.retain(|key, _| {
|
||||
!key.to_string_lossy()
|
||||
.eq_ignore_ascii_case(DESKTOP_NATIVE_NOTIFICATIONS_ENV)
|
||||
let key = key.to_string_lossy();
|
||||
!key.eq_ignore_ascii_case(DESKTOP_NATIVE_NOTIFICATIONS_ENV)
|
||||
&& !key.eq_ignore_ascii_case(DESKTOP_RUNTIME_ENV)
|
||||
});
|
||||
env.insert(
|
||||
OsString::from("KANDEV_SERVER_HOST"),
|
||||
@@ -384,6 +386,7 @@ pub fn desktop_environment(
|
||||
OsString::from(DESKTOP_NATIVE_NOTIFICATIONS_ENV),
|
||||
OsString::from("true"),
|
||||
);
|
||||
env.insert(OsString::from(DESKTOP_RUNTIME_ENV), OsString::from("true"));
|
||||
env.insert(OsString::from("PATH"), path);
|
||||
env
|
||||
}
|
||||
@@ -730,6 +733,10 @@ fn current_home_dir() -> Option<PathBuf> {
|
||||
.map(PathBuf::from)
|
||||
}
|
||||
|
||||
pub(crate) fn picker_home_dir() -> Option<PathBuf> {
|
||||
current_home_dir()
|
||||
}
|
||||
|
||||
fn executable_name(name: &str) -> OsString {
|
||||
if cfg!(windows) {
|
||||
OsString::from(format!("{name}.exe"))
|
||||
@@ -870,6 +877,10 @@ mod tests {
|
||||
.get(OsStr::new("KANDEV_DESKTOP_NATIVE_NOTIFICATIONS")),
|
||||
Some(&OsString::from("true"))
|
||||
);
|
||||
assert_eq!(
|
||||
spec.env.get(OsStr::new("KANDEV_DESKTOP_RUNTIME")),
|
||||
Some(&OsString::from("true"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
use serde::Serialize;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// The result of the deliberately narrow native folder-selection boundary.
|
||||
/// The command never accepts a path from the WebView. The selected path is
|
||||
/// returned only after the user chooses it in the operating-system picker.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(tag = "status", rename_all = "camelCase")]
|
||||
pub enum FolderPickerOutcome {
|
||||
Selected { path: String },
|
||||
Cancelled,
|
||||
Failed { message: String },
|
||||
}
|
||||
|
||||
fn outcome_from_path(path: Option<Result<PathBuf, String>>) -> FolderPickerOutcome {
|
||||
match path {
|
||||
Some(Ok(path)) => FolderPickerOutcome::Selected {
|
||||
path: path.to_string_lossy().into_owned(),
|
||||
},
|
||||
Some(Err(message)) => FolderPickerOutcome::Failed { message },
|
||||
None => FolderPickerOutcome::Cancelled,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "desktop-runtime")]
|
||||
#[tauri::command]
|
||||
pub fn pick_directory(
|
||||
app: tauri::AppHandle,
|
||||
backend: tauri::State<'_, crate::backend::BackendState>,
|
||||
webview: tauri::WebviewWindow,
|
||||
) -> Result<FolderPickerOutcome, String> {
|
||||
use tauri_plugin_dialog::{DialogExt, FilePath};
|
||||
|
||||
backend.require_owned_origin(&webview)?;
|
||||
let home = crate::backend::picker_home_dir()
|
||||
.ok_or_else(|| "could not determine the desktop user's home directory".to_string())?;
|
||||
let picked = app
|
||||
.dialog()
|
||||
.file()
|
||||
.set_directory(home)
|
||||
.set_parent(&webview)
|
||||
.blocking_pick_folder();
|
||||
let result = picked.map(|path: FilePath| path.into_path().map_err(|err| err.to_string()));
|
||||
Ok(outcome_from_path(result))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn maps_a_selected_directory() {
|
||||
assert_eq!(
|
||||
outcome_from_path(Some(Ok(PathBuf::from("/Users/example/Code")))),
|
||||
FolderPickerOutcome::Selected {
|
||||
path: "/Users/example/Code".to_string()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_cancellation_without_a_path() {
|
||||
assert_eq!(outcome_from_path(None), FolderPickerOutcome::Cancelled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_picker_failures_without_exposing_a_path_argument() {
|
||||
assert_eq!(
|
||||
outcome_from_path(Some(Err("picker unavailable".to_string()))),
|
||||
FolderPickerOutcome::Failed {
|
||||
message: "picker unavailable".to_string()
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod backend;
|
||||
pub mod external_links;
|
||||
pub mod folder_picker;
|
||||
pub mod native_notifications;
|
||||
pub mod shell;
|
||||
pub mod updater;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use kandev_desktop::{
|
||||
backend, external_links,
|
||||
backend, external_links, folder_picker,
|
||||
native_notifications::{self, NativeNotificationState},
|
||||
shell::{self, MenuAction, ZoomState},
|
||||
updater::{self, UpdaterState},
|
||||
@@ -22,6 +22,7 @@ fn main() {
|
||||
let app = tauri::Builder::default()
|
||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||
.plugin(tauri_plugin_notification::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(
|
||||
tauri_plugin_opener::Builder::new()
|
||||
.open_js_links_on_click(false)
|
||||
@@ -42,6 +43,7 @@ fn main() {
|
||||
native_notifications::get_native_notification_permission,
|
||||
native_notifications::request_native_notification_permission,
|
||||
external_links::open_external_url,
|
||||
folder_picker::pick_directory,
|
||||
])
|
||||
.menu(build_menu)
|
||||
.on_menu_event(handle_menu_event)
|
||||
|
||||
@@ -58,6 +58,9 @@
|
||||
"digestAlgorithm": "sha256",
|
||||
"timestampUrl": "https://timestamp.digicert.com",
|
||||
"signCommand": "powershell -NoProfile -ExecutionPolicy Bypass -File ./windows-sign.ps1 %1"
|
||||
},
|
||||
"macOS": {
|
||||
"infoPlist": "Info.plist"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"use server";
|
||||
|
||||
import { fetchJson } from "@/lib/api/client";
|
||||
import { getBackendConfig } from "@/lib/config";
|
||||
import type { DesktopDiscoveryRoot, RepositoryDiscoveryResponse } from "@/lib/types/http";
|
||||
|
||||
const { apiBaseUrl } = getBackendConfig();
|
||||
|
||||
export type RepositoryDiscoveryRefreshTrigger = "manual_refresh" | "stale_refresh";
|
||||
|
||||
export async function getRepositoryDiscoveryAction(
|
||||
workspaceId: string,
|
||||
root?: string,
|
||||
): Promise<RepositoryDiscoveryResponse> {
|
||||
const params = root ? `?root=${encodeURIComponent(root)}` : "";
|
||||
return fetchJson<RepositoryDiscoveryResponse>(
|
||||
`${apiBaseUrl}/api/v1/workspaces/${workspaceId}/repositories/discovery${params}`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function refreshRepositoryDiscoveryAction(
|
||||
workspaceId: string,
|
||||
root?: string,
|
||||
trigger: RepositoryDiscoveryRefreshTrigger = "manual_refresh",
|
||||
): Promise<RepositoryDiscoveryResponse> {
|
||||
const params = new URLSearchParams();
|
||||
if (root) params.set("root", root);
|
||||
params.set("trigger", trigger);
|
||||
return fetchJson<RepositoryDiscoveryResponse>(
|
||||
`${apiBaseUrl}/api/v1/workspaces/${workspaceId}/repositories/discovery/refresh?${params.toString()}`,
|
||||
{ init: { method: "POST" } },
|
||||
);
|
||||
}
|
||||
|
||||
export async function listDesktopDiscoveryRootsAction(): Promise<{
|
||||
roots: DesktopDiscoveryRoot[];
|
||||
}> {
|
||||
return fetchJson<{ roots: DesktopDiscoveryRoot[] }>(
|
||||
`${apiBaseUrl}/api/v1/repositories/discovery/roots`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function addDesktopDiscoveryRootAction(path: string): Promise<DesktopDiscoveryRoot> {
|
||||
return fetchJson<DesktopDiscoveryRoot>(`${apiBaseUrl}/api/v1/repositories/discovery/roots`, {
|
||||
init: { method: "POST", body: JSON.stringify({ path }) },
|
||||
});
|
||||
}
|
||||
|
||||
export async function reconnectDesktopDiscoveryRootAction(
|
||||
oldPath: string,
|
||||
newPath: string,
|
||||
): Promise<DesktopDiscoveryRoot> {
|
||||
return fetchJson<DesktopDiscoveryRoot>(
|
||||
`${apiBaseUrl}/api/v1/repositories/discovery/roots/reconnect`,
|
||||
{ init: { method: "POST", body: JSON.stringify({ path: oldPath, new_path: newPath }) } },
|
||||
);
|
||||
}
|
||||
|
||||
export async function removeDesktopDiscoveryRootAction(path: string): Promise<void> {
|
||||
await fetchJson<void>(
|
||||
`${apiBaseUrl}/api/v1/repositories/discovery/roots?path=${encodeURIComponent(path)}`,
|
||||
{ init: { method: "DELETE" } },
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
/* eslint-disable max-lines -- Workspace and workflow actions share one server-action boundary. */
|
||||
|
||||
"use server";
|
||||
|
||||
import { getBackendConfig } from "@/lib/config";
|
||||
@@ -233,6 +235,15 @@ export async function discoverRepositoriesAction(
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
getRepositoryDiscoveryAction,
|
||||
refreshRepositoryDiscoveryAction,
|
||||
listDesktopDiscoveryRootsAction,
|
||||
addDesktopDiscoveryRootAction,
|
||||
reconnectDesktopDiscoveryRootAction,
|
||||
removeDesktopDiscoveryRootAction,
|
||||
} from "./repository-discovery";
|
||||
|
||||
export async function validateRepositoryPathAction(
|
||||
workspaceId: string,
|
||||
path: string,
|
||||
|
||||
@@ -18,6 +18,7 @@ import type { Repository } from "@/lib/types/http";
|
||||
import { normalizeRepoValue, shouldShowCustomEntry } from "./repo-entry";
|
||||
import { useDiscoveredRepositories } from "./use-discovered-repositories";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { RepositoryDiscoveryControls } from "@/components/repository-discovery-controls";
|
||||
|
||||
type Props = {
|
||||
workspaceId: string | null;
|
||||
@@ -117,6 +118,11 @@ export function ProjectRepositoryPicker({
|
||||
<TooltipContent>{t("office:pickAWorkspaceRepoADiscovered")}</TooltipContent>
|
||||
</Tooltip>
|
||||
<PopoverContent className="w-[420px] p-0" align="start" portal={false}>
|
||||
<RepositoryDiscoveryControls
|
||||
workspaceId={workspaceId}
|
||||
enabled={open}
|
||||
presentation="picker"
|
||||
/>
|
||||
<Command>
|
||||
<CommandInput
|
||||
placeholder={t("office:searchOrPasteAUrlOr")}
|
||||
|
||||
@@ -1,23 +1,30 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { useDiscoveredRepositories } from "./use-discovered-repositories";
|
||||
import { discoverRepositoriesAction } from "@/app/actions/workspaces";
|
||||
import type { LocalRepository } from "@/lib/types/http";
|
||||
import {
|
||||
getRepositoryDiscoveryAction,
|
||||
refreshRepositoryDiscoveryAction,
|
||||
} from "@/app/actions/workspaces";
|
||||
import { repositoryDiscoveryCoordinator } from "@/hooks/domains/workspace/use-repository-discovery";
|
||||
|
||||
vi.mock("@/app/actions/workspaces", () => ({
|
||||
discoverRepositoriesAction: vi.fn(),
|
||||
getRepositoryDiscoveryAction: vi.fn(),
|
||||
refreshRepositoryDiscoveryAction: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockDiscover = vi.mocked(discoverRepositoriesAction);
|
||||
const mockDiscover = vi.mocked(getRepositoryDiscoveryAction);
|
||||
|
||||
const repoA: LocalRepository = { path: "/work/a", name: "a", default_branch: "main" };
|
||||
const repoB: LocalRepository = { path: "/work/b", name: "b", default_branch: "main" };
|
||||
|
||||
function deferred() {
|
||||
let resolve!: (v: { repositories: LocalRepository[] }) => void;
|
||||
const promise = new Promise<{ repositories: LocalRepository[] }>((r) => {
|
||||
resolve = r;
|
||||
});
|
||||
let resolve!: (v: { roots: never[]; repositories: LocalRepository[]; total: number }) => void;
|
||||
const promise = new Promise<{ roots: never[]; repositories: LocalRepository[]; total: number }>(
|
||||
(r) => {
|
||||
resolve = r;
|
||||
},
|
||||
);
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
@@ -32,11 +39,17 @@ function renderDiscovery(open: boolean, ws: string | null) {
|
||||
|
||||
describe("useDiscoveredRepositories", () => {
|
||||
beforeEach(() => {
|
||||
repositoryDiscoveryCoordinator.dispose();
|
||||
mockDiscover.mockReset();
|
||||
vi.mocked(refreshRepositoryDiscoveryAction).mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
repositoryDiscoveryCoordinator.dispose();
|
||||
});
|
||||
|
||||
it("returns null until discovery resolves, then the repos", async () => {
|
||||
mockDiscover.mockResolvedValue({ repositories: [repoA] } as never);
|
||||
mockDiscover.mockResolvedValue({ roots: [], repositories: [repoA], total: 1 } as never);
|
||||
const { result } = renderDiscovery(true, "ws1");
|
||||
expect(result.current).toBeNull();
|
||||
await waitFor(() => expect(result.current).toEqual([repoA]));
|
||||
@@ -48,27 +61,28 @@ describe("useDiscoveredRepositories", () => {
|
||||
expect(mockDiscover).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retries after a request interrupted by closing the popover", async () => {
|
||||
it("keeps the cached result after closing and reopening the popover", async () => {
|
||||
const first = deferred();
|
||||
mockDiscover.mockReturnValueOnce(first.promise as never);
|
||||
const { result, rerender } = renderDiscovery(true, "ws1");
|
||||
|
||||
// Close before the first request resolves — its response is discarded.
|
||||
// Close before the first request resolves. The coordinator keeps the
|
||||
// response because it is a cache, not a component-local request.
|
||||
rerender({ o: false, w: "ws1" });
|
||||
await act(async () => first.resolve({ repositories: [repoA] }));
|
||||
await act(async () => first.resolve({ roots: [], repositories: [repoA], total: 1 }));
|
||||
expect(result.current).toBeNull();
|
||||
|
||||
// Reopen: must refetch instead of latching "searching" forever.
|
||||
mockDiscover.mockResolvedValueOnce({ repositories: [repoB] } as never);
|
||||
// Reopen: the cached result is immediately available and no second scan
|
||||
// is needed while the cache is fresh.
|
||||
rerender({ o: true, w: "ws1" });
|
||||
await waitFor(() => expect(result.current).toEqual([repoB]));
|
||||
expect(mockDiscover).toHaveBeenCalledTimes(2);
|
||||
await waitFor(() => expect(result.current).toEqual([repoA]));
|
||||
expect(mockDiscover).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("never surfaces another workspace's results after a switch", async () => {
|
||||
const slowWs1 = deferred();
|
||||
mockDiscover.mockReturnValueOnce(slowWs1.promise as never);
|
||||
mockDiscover.mockResolvedValueOnce({ repositories: [repoB] } as never);
|
||||
mockDiscover.mockResolvedValueOnce({ roots: [], repositories: [repoB], total: 1 } as never);
|
||||
const { result, rerender } = renderDiscovery(true, "ws1");
|
||||
|
||||
// Switch workspaces while ws1's request is still in flight.
|
||||
@@ -77,7 +91,7 @@ describe("useDiscoveredRepositories", () => {
|
||||
await waitFor(() => expect(result.current).toEqual([repoB]));
|
||||
|
||||
// ws1's late response must not clobber ws2's result.
|
||||
await act(async () => slowWs1.resolve({ repositories: [repoA] }));
|
||||
await act(async () => slowWs1.resolve({ roots: [], repositories: [repoA], total: 1 }));
|
||||
expect(result.current).toEqual([repoB]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { discoverRepositoriesAction } from "@/app/actions/workspaces";
|
||||
import { useRepositoryDiscovery } from "@/hooks/domains/workspace/use-repository-discovery";
|
||||
import type { LocalRepository } from "@/lib/types/http";
|
||||
|
||||
type DiscoveryResult = { ws: string; repos: LocalRepository[] };
|
||||
|
||||
/**
|
||||
* Lazily discovers on-disk repositories while the picker popover is
|
||||
* open. Returns `null` until the current workspace's discovery has
|
||||
@@ -22,23 +19,7 @@ export function useDiscoveredRepositories(
|
||||
open: boolean,
|
||||
workspaceId: string | null,
|
||||
): LocalRepository[] | null {
|
||||
const [result, setResult] = useState<DiscoveryResult | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !workspaceId) return;
|
||||
if (result?.ws === workspaceId) return;
|
||||
let cancelled = false;
|
||||
discoverRepositoriesAction(workspaceId)
|
||||
.then((res) => {
|
||||
if (!cancelled) setResult({ ws: workspaceId, repos: res.repositories ?? [] });
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setResult({ ws: workspaceId, repos: [] });
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open, workspaceId, result]);
|
||||
|
||||
return result?.ws === workspaceId ? result.repos : null;
|
||||
const discovery = useRepositoryDiscovery(workspaceId, open);
|
||||
if (!open || !workspaceId || !discovery.hasSnapshot) return null;
|
||||
return discovery.repositories;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
export {
|
||||
RepositoryDiscoveryRootControls,
|
||||
type RepositoryDiscoveryRootControlsProps,
|
||||
} from "@/components/repository-discovery-root-controls";
|
||||
@@ -0,0 +1 @@
|
||||
export { useDiscoveryRootActions } from "@/hooks/domains/workspace/use-discovery-root-actions";
|
||||
@@ -32,6 +32,9 @@ export function AddLocalRepositoryDialog({
|
||||
isValidating={state.isValidating}
|
||||
canSave={state.canSave}
|
||||
onConfirm={state.handleConfirmLocalRepository}
|
||||
desktopRuntime={state.desktopRuntime}
|
||||
workspaceId={state.workspaceId}
|
||||
onRefreshDiscovery={state.onRefreshDiscovery}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,11 +16,11 @@ import {
|
||||
createRepositoryScriptAction,
|
||||
deleteRepositoryAction,
|
||||
deleteRepositoryScriptAction,
|
||||
discoverRepositoriesAction,
|
||||
updateRepositoryAction,
|
||||
updateRepositoryScriptAction,
|
||||
validateRepositoryPathAction,
|
||||
} from "@/app/actions/workspaces";
|
||||
import { useRepositoryDiscovery } from "@/hooks/domains/workspace/use-repository-discovery";
|
||||
import {
|
||||
repositoryId as toRepositoryId,
|
||||
type LocalRepository,
|
||||
@@ -29,7 +29,6 @@ import {
|
||||
type Workspace,
|
||||
} from "@/lib/types/http";
|
||||
import { useRequest } from "@/lib/http/use-request";
|
||||
import { useToast } from "@/components/toast-provider";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import type { ManualValidation } from "@/app/settings/workspace/workspace-repositories-dialog";
|
||||
import { WorkspaceNotFoundCard } from "@/app/settings/workspace/workspace-not-found-card";
|
||||
@@ -101,6 +100,28 @@ type RepoHandlerArgs = {
|
||||
clearRepositoryScripts: (id: string) => void;
|
||||
};
|
||||
|
||||
function selectDiscoveredRepository(
|
||||
path: string,
|
||||
setSelectedRepoPath: React.Dispatch<React.SetStateAction<string | null>>,
|
||||
setManualRepoPath: React.Dispatch<React.SetStateAction<string>>,
|
||||
setManualValidation: React.Dispatch<React.SetStateAction<ManualValidation>>,
|
||||
) {
|
||||
setSelectedRepoPath(path);
|
||||
setManualRepoPath("");
|
||||
setManualValidation({ status: "idle" });
|
||||
}
|
||||
|
||||
function changeManualRepositoryPath(
|
||||
value: string,
|
||||
setSelectedRepoPath: React.Dispatch<React.SetStateAction<string | null>>,
|
||||
setManualRepoPath: React.Dispatch<React.SetStateAction<string>>,
|
||||
setManualValidation: React.Dispatch<React.SetStateAction<ManualValidation>>,
|
||||
) {
|
||||
setManualRepoPath(value);
|
||||
setSelectedRepoPath(null);
|
||||
setManualValidation({ status: "idle" });
|
||||
}
|
||||
|
||||
async function saveNewRepository(
|
||||
repo: RepositoryItem,
|
||||
repoId: string,
|
||||
@@ -316,19 +337,15 @@ function useRepositoryHandlers({
|
||||
};
|
||||
}
|
||||
|
||||
function useDiscoverDialog(
|
||||
workspace: Workspace | null,
|
||||
toast: ReturnType<typeof useToast>["toast"],
|
||||
t: TFunction,
|
||||
) {
|
||||
function useDiscoverDialog(workspace: Workspace | null, t: TFunction) {
|
||||
const [localRepoDialogOpen, setLocalRepoDialogOpen] = useState(false);
|
||||
const [discoveredRepositories, setDiscoveredRepositories] = useState<LocalRepository[]>([]);
|
||||
const [repoSearch, setRepoSearch] = useState("");
|
||||
const [selectedRepoPath, setSelectedRepoPath] = useState<string | null>(null);
|
||||
const [manualRepoPath, setManualRepoPath] = useState("");
|
||||
const [manualValidation, setManualValidation] = useState<ManualValidation>({ status: "idle" });
|
||||
const discoverRequest = useRequest(discoverRepositoriesAction);
|
||||
const validateRequest = useRequest(validateRepositoryPathAction);
|
||||
const discovery = useRepositoryDiscovery(workspace?.id ?? null, localRepoDialogOpen);
|
||||
const discoveredRepositories = discovery.repositories;
|
||||
|
||||
const filteredRepositories = useMemo(() => {
|
||||
const query = repoSearch.trim().toLowerCase();
|
||||
@@ -340,25 +357,15 @@ function useDiscoverDialog(
|
||||
|
||||
const handleDiscover = async () => {
|
||||
if (!workspace) return;
|
||||
try {
|
||||
const result = await discoverRequest.run(workspace.id);
|
||||
setDiscoveredRepositories(result.repositories);
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t("workspaces:failedToDiscoverRepositories"),
|
||||
description: error instanceof Error ? error.message : t("common:requestFailed"),
|
||||
variant: "error",
|
||||
});
|
||||
}
|
||||
await discovery.refresh();
|
||||
};
|
||||
|
||||
const openDialog = async () => {
|
||||
const openDialog = () => {
|
||||
setLocalRepoDialogOpen(true);
|
||||
setRepoSearch("");
|
||||
setSelectedRepoPath(null);
|
||||
setManualRepoPath("");
|
||||
setManualValidation({ status: "idle" });
|
||||
await handleDiscover();
|
||||
};
|
||||
|
||||
const handleValidateManualPath = async () => {
|
||||
@@ -391,16 +398,10 @@ function useDiscoverDialog(
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectRepoPath = (path: string) => {
|
||||
setSelectedRepoPath(path);
|
||||
setManualRepoPath("");
|
||||
setManualValidation({ status: "idle" });
|
||||
};
|
||||
const handleManualRepoPathChange = (value: string) => {
|
||||
setManualRepoPath(value);
|
||||
setSelectedRepoPath(null);
|
||||
setManualValidation({ status: "idle" });
|
||||
};
|
||||
const handleSelectRepoPath = (path: string) =>
|
||||
selectDiscoveredRepository(path, setSelectedRepoPath, setManualRepoPath, setManualValidation);
|
||||
const handleManualRepoPathChange = (value: string) =>
|
||||
changeManualRepositoryPath(value, setSelectedRepoPath, setManualRepoPath, setManualValidation);
|
||||
const canSave =
|
||||
Boolean(selectedRepoPath) ||
|
||||
(manualValidation.status === "success" && manualValidation.isValid === true);
|
||||
@@ -418,10 +419,13 @@ function useDiscoverDialog(
|
||||
manualValidation,
|
||||
handleValidateManualPath,
|
||||
isValidating: validateRequest.isLoading,
|
||||
isDiscovering: discoverRequest.isLoading,
|
||||
isDiscovering: discovery.isLoading || discovery.isRefreshing,
|
||||
canSave,
|
||||
openDialog,
|
||||
discoveredRepositories,
|
||||
desktopRuntime: discovery.desktopRuntime,
|
||||
onRefreshDiscovery: () => void handleDiscover(),
|
||||
workspaceId: workspace?.id ?? null,
|
||||
};
|
||||
}
|
||||
export function useWorkspaceRepositoriesPage(
|
||||
@@ -429,7 +433,6 @@ export function useWorkspaceRepositoriesPage(
|
||||
repositories: RepositoryWithScripts[],
|
||||
) {
|
||||
const router = useRouter();
|
||||
const { toast } = useToast();
|
||||
const { t } = useTranslation();
|
||||
const clearRepositoryScripts = useAppStore((state) => state.clearRepositoryScripts);
|
||||
const [repositoryItems, setRepositoryItems] = useState<RepositoryItem[]>(repositories);
|
||||
@@ -457,23 +460,12 @@ export function useWorkspaceRepositoriesPage(
|
||||
handleDeleteRepository,
|
||||
} = handlers;
|
||||
|
||||
const discover = useDiscoverDialog(workspace, toast, t);
|
||||
const discover = useDiscoverDialog(workspace, t);
|
||||
const {
|
||||
localRepoDialogOpen,
|
||||
setLocalRepoDialogOpen,
|
||||
filteredRepositories,
|
||||
repoSearch,
|
||||
setRepoSearch,
|
||||
selectedRepoPath,
|
||||
handleSelectRepoPath,
|
||||
manualRepoPath,
|
||||
handleManualRepoPathChange,
|
||||
manualValidation,
|
||||
handleValidateManualPath,
|
||||
isValidating,
|
||||
isDiscovering,
|
||||
canSave,
|
||||
openDialog,
|
||||
discoveredRepositories,
|
||||
} = discover;
|
||||
|
||||
@@ -492,7 +484,6 @@ export function useWorkspaceRepositoriesPage(
|
||||
|
||||
return {
|
||||
router,
|
||||
toast,
|
||||
repositoryItems,
|
||||
savedRepositoriesById,
|
||||
handleUpdateRepository,
|
||||
@@ -501,21 +492,7 @@ export function useWorkspaceRepositoriesPage(
|
||||
handleDeleteRepositoryScript,
|
||||
handleSaveRepository,
|
||||
handleDeleteRepository,
|
||||
localRepoDialogOpen,
|
||||
setLocalRepoDialogOpen,
|
||||
filteredRepositories,
|
||||
repoSearch,
|
||||
setRepoSearch,
|
||||
selectedRepoPath,
|
||||
handleSelectRepoPath,
|
||||
manualRepoPath,
|
||||
handleManualRepoPathChange,
|
||||
manualValidation,
|
||||
handleValidateManualPath,
|
||||
isValidating,
|
||||
isDiscovering,
|
||||
canSave,
|
||||
openDialog,
|
||||
...discover,
|
||||
handleConfirmLocalRepository,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
DialogTitle,
|
||||
} from "@kandev/ui/dialog";
|
||||
import type { LocalRepository } from "@/lib/types/http";
|
||||
import { RepositoryDiscoveryControls } from "@/components/repository-discovery-controls";
|
||||
|
||||
export type ManualValidation = {
|
||||
status: "idle" | "loading" | "success" | "error";
|
||||
@@ -38,6 +39,9 @@ type DiscoverRepoDialogProps = {
|
||||
isValidating: boolean;
|
||||
canSave: boolean;
|
||||
onConfirm: () => void;
|
||||
desktopRuntime: boolean;
|
||||
workspaceId: string | null;
|
||||
onRefreshDiscovery: () => void;
|
||||
};
|
||||
|
||||
function RepoListContent({
|
||||
@@ -80,6 +84,51 @@ function RepoListContent({
|
||||
);
|
||||
}
|
||||
|
||||
function ManualRepositoryPath({
|
||||
manualRepoPath,
|
||||
onManualRepoPathChange,
|
||||
manualValidation,
|
||||
onValidateManualPath,
|
||||
isValidating,
|
||||
}: Pick<
|
||||
DiscoverRepoDialogProps,
|
||||
| "manualRepoPath"
|
||||
| "onManualRepoPathChange"
|
||||
| "manualValidation"
|
||||
| "onValidateManualPath"
|
||||
| "isValidating"
|
||||
>) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label>{t("workspaces:manualPath")}</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
{/* An absolute filesystem path is the value shape this field
|
||||
expects, not prose — left in English deliberately. */}
|
||||
<Input
|
||||
placeholder="/absolute/path/to/repository"
|
||||
value={manualRepoPath}
|
||||
onChange={(e) => onManualRepoPathChange(e.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onValidateManualPath}
|
||||
disabled={!manualRepoPath.trim() || isValidating}
|
||||
>
|
||||
{isValidating ? t("workspaces:checking") : t("workspaces:validate")}
|
||||
</Button>
|
||||
</div>
|
||||
{manualValidation.status === "error" && (
|
||||
<p className="text-xs text-destructive">{manualValidation.message}</p>
|
||||
)}
|
||||
{manualValidation.status === "success" && (
|
||||
<p className="text-xs text-emerald-500">{manualValidation.message}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DiscoverRepoDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
@@ -96,6 +145,9 @@ export function DiscoverRepoDialog({
|
||||
isValidating,
|
||||
canSave,
|
||||
onConfirm,
|
||||
desktopRuntime,
|
||||
workspaceId,
|
||||
onRefreshDiscovery,
|
||||
}: DiscoverRepoDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
@@ -106,8 +158,23 @@ export function DiscoverRepoDialog({
|
||||
<DialogDescription>{t("workspaces:discoverRepositoryDescription")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
{desktopRuntime && (
|
||||
<RepositoryDiscoveryControls workspaceId={workspaceId} enabled={open} />
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label>{t("workspaces:discoveredRepositories")}</Label>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Label>{t("workspaces:discoveredRepositories")}</Label>
|
||||
{!desktopRuntime && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="[@media(pointer:coarse)]:h-11"
|
||||
onClick={onRefreshDiscovery}
|
||||
>
|
||||
{t("workspaces:refreshRepositories")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<Input
|
||||
placeholder={t("workspaces:filterRepositories")}
|
||||
value={repoSearch}
|
||||
@@ -122,32 +189,13 @@ export function DiscoverRepoDialog({
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>{t("workspaces:manualPath")}</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
{/* An absolute filesystem path is the value shape this field
|
||||
expects, not prose — left in English deliberately. */}
|
||||
<Input
|
||||
placeholder="/absolute/path/to/repository"
|
||||
value={manualRepoPath}
|
||||
onChange={(e) => onManualRepoPathChange(e.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onValidateManualPath}
|
||||
disabled={!manualRepoPath.trim() || isValidating}
|
||||
>
|
||||
{isValidating ? t("workspaces:checking") : t("workspaces:validate")}
|
||||
</Button>
|
||||
</div>
|
||||
{manualValidation.status === "error" && (
|
||||
<p className="text-xs text-destructive">{manualValidation.message}</p>
|
||||
)}
|
||||
{manualValidation.status === "success" && (
|
||||
<p className="text-xs text-emerald-500">{manualValidation.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<ManualRepositoryPath
|
||||
manualRepoPath={manualRepoPath}
|
||||
onManualRepoPathChange={onManualRepoPathChange}
|
||||
manualValidation={manualValidation}
|
||||
onValidateManualPath={onValidateManualPath}
|
||||
isValidating={isValidating}
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
|
||||
@@ -92,6 +92,8 @@ vi.mock("@/hooks/domains/workspace/use-repositories", () => ({
|
||||
|
||||
vi.mock("@/app/actions/workspaces", () => ({
|
||||
discoverRepositoriesAction: vi.fn().mockResolvedValue({ repositories: [] }),
|
||||
getRepositoryDiscoveryAction: vi.fn().mockResolvedValue({ repositories: [] }),
|
||||
refreshRepositoryDiscoveryAction: vi.fn().mockResolvedValue({ repositories: [] }),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/task-create-dialog-options", () => ({
|
||||
@@ -113,9 +115,11 @@ vi.mock("@/components/task-create-dialog-workspace-repo-chips", () => ({
|
||||
WorkspaceRepoChips: ({
|
||||
rows,
|
||||
onAdd,
|
||||
showDiscoveryControls,
|
||||
}: {
|
||||
rows: Array<{ key: string; branch: string }>;
|
||||
onAdd: () => void;
|
||||
showDiscoveryControls?: boolean;
|
||||
}) => (
|
||||
<div data-testid="shared-repository-chips">
|
||||
{rows.map((row) => (
|
||||
@@ -124,6 +128,7 @@ vi.mock("@/components/task-create-dialog-workspace-repo-chips", () => ({
|
||||
<button type="button" onClick={onAdd}>
|
||||
Add repository
|
||||
</button>
|
||||
{showDiscoveryControls ? <div data-testid="repository-discovery-selector-enabled" /> : null}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
@@ -182,6 +187,7 @@ describe("ConfigSection shared task selectors", () => {
|
||||
renderConfig();
|
||||
|
||||
expect(screen.getByTestId("shared-repository-chips")).toBeTruthy();
|
||||
expect(screen.getByTestId("repository-discovery-selector-enabled")).toBeTruthy();
|
||||
expect(screen.queryByText("Use workspace default")).toBeNull();
|
||||
expect(
|
||||
screen.getByText("Run without repository files in a task-owned scratch workspace."),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Label } from "@kandev/ui/label";
|
||||
import { SettingsFieldLabel } from "@/components/settings/settings-typography";
|
||||
@@ -8,7 +8,7 @@ import { settingsControlClassName } from "@/components/settings/settings-control
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { useSettingsData } from "@/hooks/domains/settings/use-settings-data";
|
||||
import { useRepositories } from "@/hooks/domains/workspace/use-repositories";
|
||||
import { discoverRepositoriesAction } from "@/app/actions/workspaces";
|
||||
import { useRepositoryDiscovery } from "@/hooks/domains/workspace/use-repository-discovery";
|
||||
import type { Executor, ExecutorProfile, LocalRepository, Repository } from "@/lib/types/http";
|
||||
import type { TaskMode } from "@/lib/types/automation";
|
||||
import type { TaskRepoRow } from "@/components/task-create-dialog-types";
|
||||
@@ -64,25 +64,6 @@ const CLEAN_FIELDS = {
|
||||
repositorySelections: false,
|
||||
};
|
||||
|
||||
function useDiscoveredRepositories(workspaceId: string) {
|
||||
const [items, setItems] = useState<LocalRepository[]>([]);
|
||||
useEffect(() => {
|
||||
if (!workspaceId) return;
|
||||
let cancelled = false;
|
||||
discoverRepositoriesAction(workspaceId)
|
||||
.then((response) => {
|
||||
if (!cancelled) setItems(response.repositories ?? []);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setItems([]);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [workspaceId]);
|
||||
return items;
|
||||
}
|
||||
|
||||
function executorProfiles(executors: Executor[]): ExecutorProfile[] {
|
||||
return executors.flatMap((executor) =>
|
||||
(executor.profiles ?? []).map((profile) => ({
|
||||
@@ -147,6 +128,7 @@ function RepositoryAccess({
|
||||
repositories={repositories}
|
||||
discoveredRepositories={discovered}
|
||||
workspaceId={workspaceId}
|
||||
showDiscoveryControls
|
||||
canAddMore={supportsMultiRepo || rows.length === 0}
|
||||
addLabel={t("task:addRepository")}
|
||||
allowDuplicateRepositories={false}
|
||||
@@ -197,7 +179,7 @@ export function ConfigSection({
|
||||
);
|
||||
const snapshots = useAppStore((state) => state.kanbanMulti.snapshots);
|
||||
const { repositories } = useRepositories(workspaceId, true);
|
||||
const discovered = useDiscoveredRepositories(workspaceId);
|
||||
const discovered = useRepositoryDiscovery(workspaceId, true).repositories;
|
||||
const agentProfiles = useAppStore((state) => state.agentProfiles.items);
|
||||
const executors = useAppStore((state) => state.executors.items);
|
||||
const agents = useAgentProfileOptions(agentProfiles);
|
||||
|
||||
@@ -45,6 +45,8 @@ afterEach(() => {
|
||||
cleanup();
|
||||
mockedListDirectory.mockReset();
|
||||
setPopoverOpen = undefined;
|
||||
delete (window as Window & { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__;
|
||||
delete (window as Window & { __KANDEV_BOOT_PAYLOAD__?: unknown }).__KANDEV_BOOT_PAYLOAD__;
|
||||
});
|
||||
|
||||
describe("FolderPicker", () => {
|
||||
@@ -60,6 +62,27 @@ describe("FolderPicker", () => {
|
||||
expect(screen.getByTestId(TRIGGER_TEST_ID).textContent).toBe("C:\\");
|
||||
});
|
||||
|
||||
it("uses the native picker in a Tauri WebView without listing directories over HTTP", async () => {
|
||||
const invoke = vi.fn(async () => ({ status: "selected", path: "/Users/example/Code" }));
|
||||
Object.defineProperty(window, "__TAURI_INTERNALS__", {
|
||||
configurable: true,
|
||||
value: { invoke },
|
||||
});
|
||||
Object.defineProperty(window, "__KANDEV_BOOT_PAYLOAD__", {
|
||||
configurable: true,
|
||||
value: { runtime: { nativeFolderPickerAvailable: true } },
|
||||
});
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(<FolderPicker value="" onChange={onChange} />);
|
||||
fireEvent.click(screen.getByTestId(TRIGGER_TEST_ID));
|
||||
|
||||
await waitFor(() => expect(onChange).toHaveBeenCalledWith("/Users/example/Code"));
|
||||
expect(invoke).toHaveBeenCalledWith("pick_directory", undefined);
|
||||
expect(mockedListDirectory).not.toHaveBeenCalled();
|
||||
expect(screen.queryByTestId("folder-picker-popover")).toBeNull();
|
||||
});
|
||||
|
||||
it("builds Windows breadcrumbs with a virtual root and native drive paths", async () => {
|
||||
mockedListDirectory
|
||||
.mockResolvedValueOnce(
|
||||
|
||||
@@ -15,6 +15,12 @@ import { Popover, PopoverContent, PopoverTrigger } from "@kandev/ui/popover";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { listDirectory, type DirectoryListing } from "@/lib/api/domains/fs-api";
|
||||
import {
|
||||
isTauriWebview,
|
||||
nativeFolderPicker,
|
||||
NativeFolderPickerUnavailableError,
|
||||
} from "@/lib/desktop/folder-picker";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
type FolderPickerProps = {
|
||||
@@ -25,6 +31,64 @@ type FolderPickerProps = {
|
||||
placeholder?: string;
|
||||
};
|
||||
|
||||
type NativeFolderPickerTriggerProps = {
|
||||
triggerClass: string;
|
||||
hasValue: boolean;
|
||||
triggerLabel: string;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
onChoose: () => void;
|
||||
};
|
||||
|
||||
function NativeFolderPickerTrigger({
|
||||
triggerClass,
|
||||
hasValue,
|
||||
triggerLabel,
|
||||
loading,
|
||||
error,
|
||||
onChoose,
|
||||
}: NativeFolderPickerTriggerProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col items-start gap-1">
|
||||
<button
|
||||
type="button"
|
||||
data-testid="folder-picker-trigger"
|
||||
className={triggerClass}
|
||||
disabled={loading}
|
||||
aria-busy={loading}
|
||||
onClick={onChoose}
|
||||
>
|
||||
{hasValue ? (
|
||||
<IconFolder className="h-3.5 w-3.5 flex-shrink-0" />
|
||||
) : (
|
||||
<IconBox className="h-3.5 w-3.5 flex-shrink-0" />
|
||||
)}
|
||||
<span className="truncate max-w-[260px]">
|
||||
{loading ? t("common:loading") : triggerLabel}
|
||||
</span>
|
||||
</button>
|
||||
{error && (
|
||||
<p
|
||||
role="alert"
|
||||
data-testid="folder-picker-native-error"
|
||||
className="text-xs text-destructive"
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function nativePickerErrorMessage(error: unknown, t: TFunction): string {
|
||||
if (error instanceof NativeFolderPickerUnavailableError) {
|
||||
return t("common:nativeFolderPickerUnavailable");
|
||||
}
|
||||
if (error instanceof Error && error.message) return error.message;
|
||||
return t("common:nativeFolderPickerFailed");
|
||||
}
|
||||
|
||||
/**
|
||||
* Folder picker for repo-less tasks. Drives GET /api/v1/fs/list-dir on the
|
||||
* local kandev backend (browsers can't enumerate the host filesystem). The
|
||||
@@ -33,13 +97,16 @@ type FolderPickerProps = {
|
||||
export function FolderPicker({ value, onChange, placeholder }: FolderPickerProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const { listing, loading, error, load } = useDirectoryListing(open, value);
|
||||
const [nativeLoading, setNativeLoading] = useState(false);
|
||||
const [nativeError, setNativeError] = useState<string | null>(null);
|
||||
const tauriWebview = isTauriWebview();
|
||||
const { listing, loading, error, load } = useDirectoryListing(open && !tauriWebview, value);
|
||||
const leaf = leafName(value);
|
||||
const triggerLabel = leaf || placeholder || t("common:scratchWorkspace");
|
||||
const hasValue = !!value;
|
||||
|
||||
const triggerClass = cn(
|
||||
"h-7 inline-flex items-center gap-1.5 rounded-md px-2.5 text-xs cursor-pointer",
|
||||
"h-7 inline-flex items-center gap-1.5 rounded-md px-2.5 text-xs cursor-pointer [@media(pointer:coarse)]:h-11",
|
||||
"border border-border/60 transition-colors",
|
||||
hasValue
|
||||
? "bg-primary/10 text-foreground hover:bg-primary/15"
|
||||
@@ -57,6 +124,39 @@ export function FolderPicker({ value, onChange, placeholder }: FolderPickerProps
|
||||
</button>
|
||||
);
|
||||
|
||||
const chooseNativeFolder = async () => {
|
||||
setNativeError(null);
|
||||
if (!nativeFolderPicker.isAvailable()) {
|
||||
setNativeError(t("common:nativeFolderPickerUnavailable"));
|
||||
return;
|
||||
}
|
||||
setNativeLoading(true);
|
||||
try {
|
||||
const outcome = await nativeFolderPicker.pickDirectory();
|
||||
if (outcome.status === "selected") onChange(outcome.path);
|
||||
if (outcome.status === "failed") {
|
||||
setNativeError(outcome.message || t("common:nativeFolderPickerFailed"));
|
||||
}
|
||||
} catch (error) {
|
||||
setNativeError(nativePickerErrorMessage(error, t));
|
||||
} finally {
|
||||
setNativeLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (tauriWebview) {
|
||||
return (
|
||||
<NativeFolderPickerTrigger
|
||||
triggerClass={triggerClass}
|
||||
hasValue={hasValue}
|
||||
triggerLabel={triggerLabel}
|
||||
loading={nativeLoading}
|
||||
error={nativeError}
|
||||
onChoose={() => void chooseNativeFolder()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const discovery = vi.hoisted(() => ({
|
||||
desktopRuntime: true,
|
||||
isLoading: false,
|
||||
isRefreshing: false,
|
||||
rootStates: [
|
||||
{ id: "root-1", path: "/projects", display_path: "~/projects", state: "connected" },
|
||||
{ id: "", path: "/configured", display_path: "/configured", state: "connected" },
|
||||
],
|
||||
homeConfirmationRequired: true,
|
||||
}));
|
||||
const actions = vi.hoisted(() => ({
|
||||
refreshDiscovery: vi.fn(),
|
||||
handleChooseDiscoveryRoot: vi.fn(),
|
||||
handleReconnectDiscoveryRoot: vi.fn(),
|
||||
handleRemoveDiscoveryRoot: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/domains/workspace/use-repository-discovery", () => ({
|
||||
useRepositoryDiscovery: () => discovery,
|
||||
}));
|
||||
vi.mock("@/hooks/domains/workspace/use-discovery-root-actions", () => ({
|
||||
useDiscoveryRootActions: () => actions,
|
||||
}));
|
||||
vi.mock("@/components/toast-provider", () => ({
|
||||
useToast: () => ({ toast: vi.fn() }),
|
||||
}));
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
vi.mock("@/components/repository-discovery-root-controls", () => ({
|
||||
RepositoryDiscoveryRootControls: (props: {
|
||||
discoveryRoots: Array<{ id: string }>;
|
||||
onChooseDiscoveryRoot: (path: string) => void;
|
||||
}) => (
|
||||
<div data-testid="root-controls">
|
||||
<span data-testid="root-count">{props.discoveryRoots.length}</span>
|
||||
<button type="button" onClick={() => props.onChooseDiscoveryRoot("/picked")}>
|
||||
Choose
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
import { RepositoryDiscoveryControls } from "./repository-discovery-controls";
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("RepositoryDiscoveryControls", () => {
|
||||
it("renders the shared desktop consent surface and only exposes operator roots", () => {
|
||||
render(<RepositoryDiscoveryControls workspaceId="workspace-1" />);
|
||||
|
||||
expect(screen.getByTestId("root-controls")).toBeTruthy();
|
||||
expect(screen.getByTestId("root-count").textContent).toBe("1");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Choose" }));
|
||||
expect(actions.handleChooseDiscoveryRoot).toHaveBeenCalledWith("/picked");
|
||||
});
|
||||
|
||||
it("does not lease or render a surface when disabled", () => {
|
||||
render(<RepositoryDiscoveryControls workspaceId="workspace-1" enabled={false} />);
|
||||
|
||||
expect(screen.queryByTestId("root-controls")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
"use client";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useToast } from "@/components/toast-provider";
|
||||
import { useRepositoryDiscovery } from "@/hooks/domains/workspace/use-repository-discovery";
|
||||
import { useDiscoveryRootActions } from "@/hooks/domains/workspace/use-discovery-root-actions";
|
||||
import { RepositoryDiscoveryRootControls } from "@/components/repository-discovery-root-controls";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type RepositoryDiscoveryControlsProps = {
|
||||
workspaceId: string | null;
|
||||
enabled?: boolean;
|
||||
className?: string;
|
||||
presentation?: "card" | "picker";
|
||||
};
|
||||
|
||||
/**
|
||||
* The shared consent and recovery surface for every repository selector.
|
||||
* Keeping the discovery lease and root actions together prevents a picker
|
||||
* from showing an empty result without also offering the action that can
|
||||
* establish or repair its filesystem access.
|
||||
*/
|
||||
export function RepositoryDiscoveryControls({
|
||||
workspaceId,
|
||||
enabled = true,
|
||||
className,
|
||||
presentation = "card",
|
||||
}: RepositoryDiscoveryControlsProps) {
|
||||
const discovery = useRepositoryDiscovery(workspaceId, enabled);
|
||||
const { toast } = useToast();
|
||||
const { t } = useTranslation();
|
||||
const actions = useDiscoveryRootActions(discovery, toast, t);
|
||||
|
||||
if (!enabled || !workspaceId || !discovery.desktopRuntime) return null;
|
||||
|
||||
return (
|
||||
<RepositoryDiscoveryRootControls
|
||||
className={cn("w-full", className)}
|
||||
presentation={presentation}
|
||||
isLoading={discovery.isLoading || discovery.isRefreshing}
|
||||
discoveryRoots={discovery.rootStates.filter((root) => Boolean(root.id))}
|
||||
homeConfirmationRequired={discovery.homeConfirmationRequired}
|
||||
onChooseDiscoveryRoot={actions.handleChooseDiscoveryRoot}
|
||||
onRefreshDiscovery={actions.refreshDiscovery}
|
||||
onReconnectDiscoveryRoot={actions.handleReconnectDiscoveryRoot}
|
||||
onRemoveDiscoveryRoot={actions.handleRemoveDiscoveryRoot}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
"use client";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import { FolderPicker } from "@/components/folder-picker";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { DesktopDiscoveryRoot } from "@/lib/types/http";
|
||||
|
||||
export type RepositoryDiscoveryRootControlsProps = {
|
||||
className?: string;
|
||||
presentation?: "card" | "picker";
|
||||
isLoading: boolean;
|
||||
discoveryRoots: DesktopDiscoveryRoot[];
|
||||
homeConfirmationRequired: boolean;
|
||||
onChooseDiscoveryRoot: (path: string) => void;
|
||||
onRefreshDiscovery: () => void;
|
||||
onReconnectDiscoveryRoot: (oldPath: string, newPath: string) => void;
|
||||
onRemoveDiscoveryRoot: (path: string) => void;
|
||||
};
|
||||
|
||||
export function RepositoryDiscoveryRootControls({
|
||||
className,
|
||||
presentation = "card",
|
||||
isLoading,
|
||||
discoveryRoots,
|
||||
homeConfirmationRequired,
|
||||
onChooseDiscoveryRoot,
|
||||
onRefreshDiscovery,
|
||||
onReconnectDiscoveryRoot,
|
||||
onRemoveDiscoveryRoot,
|
||||
}: RepositoryDiscoveryRootControlsProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
presentation === "picker"
|
||||
? "space-y-2 border-b border-border/60 bg-muted/20 p-2"
|
||||
: "space-y-2 rounded-md border border-border/60 p-3",
|
||||
className,
|
||||
)}
|
||||
data-testid="discovery-root-controls"
|
||||
data-presentation={presentation}
|
||||
>
|
||||
{presentation === "card" && (
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
{t("workspaces:chooseFoldersToDiscoverRepositories")}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("workspaces:chooseFoldersToDiscoverRepositoriesDescription")}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<FolderPicker
|
||||
value=""
|
||||
placeholder={t("workspaces:chooseFoldersToDiscoverRepositories")}
|
||||
onChange={onChooseDiscoveryRoot}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="[@media(pointer:coarse)]:h-11"
|
||||
onClick={onRefreshDiscovery}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{t("workspaces:refreshRepositories")}
|
||||
</Button>
|
||||
</div>
|
||||
{homeConfirmationRequired && (
|
||||
<div className="rounded border border-amber-500/40 bg-amber-500/10 p-2 text-xs">
|
||||
<p>{t("workspaces:homeDiscoveryConfirmationDescription")}</p>
|
||||
<div className="mt-2">
|
||||
<FolderPicker
|
||||
value=""
|
||||
placeholder={t("workspaces:continueHomeDiscovery")}
|
||||
onChange={onChooseDiscoveryRoot}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{discoveryRoots.map((root) => (
|
||||
<div
|
||||
key={root.id || root.path}
|
||||
className="flex min-w-0 flex-wrap items-center gap-2 rounded border border-border/50 p-2 text-xs"
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate font-mono" title={root.path}>
|
||||
{root.display_path || root.path}
|
||||
</span>
|
||||
{root.state === "reconnect_required" && (
|
||||
<FolderPicker
|
||||
value=""
|
||||
placeholder={t("workspaces:reconnectDiscoveryRoot")}
|
||||
onChange={(newPath) => onReconnectDiscoveryRoot(root.path, newPath)}
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="[@media(pointer:coarse)]:h-11"
|
||||
onClick={() => onRemoveDiscoveryRoot(root.path)}
|
||||
>
|
||||
{t("workspaces:removeDiscoveryRoot")}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,10 +4,7 @@ import { useEffect, useMemo, useRef } from "react";
|
||||
import type { Repository, Executor, ExecutorProfile } from "@/lib/types/http";
|
||||
import { DEFAULT_LOCAL_EXECUTOR_TYPE } from "@/lib/utils";
|
||||
import { useToast } from "@/components/toast-provider";
|
||||
import {
|
||||
discoverRepositoriesAction,
|
||||
getLocalRepositoryStatusAction,
|
||||
} from "@/app/actions/workspaces";
|
||||
import { getLocalRepositoryStatusAction } from "@/app/actions/workspaces";
|
||||
import { listWorkflowSteps } from "@/lib/api/domains/workflow-api";
|
||||
import { parseGitHubAnyUrl } from "@/hooks/domains/github/use-pr-info-by-url";
|
||||
import type {
|
||||
@@ -22,6 +19,7 @@ import {
|
||||
import { useRepositoryAutoSelectEffect } from "@/components/task-create-dialog-repository-autopick";
|
||||
import { createDebugLogger, isDebug } from "@/lib/debug/log";
|
||||
import { t } from "@/lib/i18n";
|
||||
import { useRepositoryDiscovery } from "@/hooks/domains/workspace/use-repository-discovery";
|
||||
|
||||
// Re-export autopick hooks for callers that imported them from this module.
|
||||
export { useWorkflowAgentProfileEffect };
|
||||
@@ -75,41 +73,33 @@ export function useDiscoverReposEffect(
|
||||
repositoriesLoading: boolean,
|
||||
toast: ReturnType<typeof useToast>["toast"],
|
||||
) {
|
||||
const {
|
||||
discoverReposLoaded,
|
||||
discoverReposLoading,
|
||||
setDiscoveredRepositories,
|
||||
setDiscoverReposLoading,
|
||||
setDiscoverReposLoaded,
|
||||
} = fs;
|
||||
const discovery = useRepositoryDiscovery(workspaceId, open && !repositoriesLoading);
|
||||
const { setDiscoveredRepositories, setDiscoverReposLoading, setDiscoverReposLoaded } = fs;
|
||||
const reportedErrorRef = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!open || !workspaceId || repositoriesLoading || discoverReposLoaded || discoverReposLoading)
|
||||
return;
|
||||
void Promise.resolve()
|
||||
.then(() => setDiscoverReposLoading(true))
|
||||
.then(() => discoverRepositoriesAction(workspaceId))
|
||||
.then((r) => {
|
||||
setDiscoveredRepositories(r.repositories);
|
||||
})
|
||||
.catch((e) => {
|
||||
toast({
|
||||
title: t("task:failedToDiscoverRepositories"),
|
||||
description: e instanceof Error ? e.message : t("common:requestFailed"),
|
||||
variant: "error",
|
||||
});
|
||||
setDiscoveredRepositories([]);
|
||||
})
|
||||
.finally(() => {
|
||||
setDiscoverReposLoading(false);
|
||||
setDiscoverReposLoaded(true);
|
||||
if (!open || !workspaceId || repositoriesLoading) return;
|
||||
setDiscoveredRepositories(discovery.repositories);
|
||||
setDiscoverReposLoading(discovery.isLoading || discovery.isRefreshing);
|
||||
setDiscoverReposLoaded(discovery.hasSnapshot || discovery.error !== null);
|
||||
if (discovery.error && reportedErrorRef.current !== discovery.error.message) {
|
||||
reportedErrorRef.current = discovery.error.message;
|
||||
toast({
|
||||
title: t("task:failedToDiscoverRepositories"),
|
||||
description: discovery.error.message || t("common:requestFailed"),
|
||||
variant: "error",
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}
|
||||
}, [
|
||||
discoverReposLoaded,
|
||||
discoverReposLoading,
|
||||
discovery.error,
|
||||
discovery.hasSnapshot,
|
||||
discovery.isLoading,
|
||||
discovery.isRefreshing,
|
||||
discovery.repositories,
|
||||
open,
|
||||
fs.discoveredRepositories.length,
|
||||
repositoriesLoading,
|
||||
setDiscoveredRepositories,
|
||||
setDiscoverReposLoaded,
|
||||
setDiscoverReposLoading,
|
||||
toast,
|
||||
workspaceId,
|
||||
]);
|
||||
|
||||
@@ -38,11 +38,10 @@ export type PillAction = {
|
||||
};
|
||||
|
||||
/**
|
||||
* `Pill` wraps cmdk's `Command` / `CommandInput` / `CommandList`. Its popover
|
||||
* body only supports cmdk children (`CommandItem`, etc.) — keyboard nav and
|
||||
* focus are routed through cmdk. If you need a popover with mixed content
|
||||
* (search list + a free-form `<input>`, banners, etc.), build a custom
|
||||
* `Popover` from `@kandev/ui/popover` instead of warping `Pill`.
|
||||
* `Pill` wraps cmdk's `Command` / `CommandInput` / `CommandList`. Searchable
|
||||
* content must remain cmdk children so keyboard navigation and focus stay
|
||||
* correct. Contextual controls can use `popoverHeader`, which renders outside
|
||||
* `Command`; mixed searchable content still needs a custom `Popover`.
|
||||
*/
|
||||
|
||||
type PillProps = {
|
||||
@@ -84,6 +83,8 @@ type PillProps = {
|
||||
prefix?: string;
|
||||
/** Optional icon action rendered beside the search input. */
|
||||
action?: PillAction;
|
||||
/** Optional contextual controls rendered above the searchable list. */
|
||||
popoverHeader?: React.ReactNode;
|
||||
};
|
||||
|
||||
/** Returns the active-state hover classes for the pill trigger button. */
|
||||
@@ -244,6 +245,7 @@ function PillPopoverContent({
|
||||
emptyMessage,
|
||||
portalContainer,
|
||||
action,
|
||||
popoverHeader,
|
||||
}: {
|
||||
filter?: PillProps["filter"];
|
||||
searchPlaceholder: string;
|
||||
@@ -258,6 +260,7 @@ function PillPopoverContent({
|
||||
emptyMessage: string;
|
||||
portalContainer: HTMLElement | null;
|
||||
action?: PillAction;
|
||||
popoverHeader?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<PopoverContent
|
||||
@@ -265,6 +268,7 @@ function PillPopoverContent({
|
||||
align="start"
|
||||
portalContainer={portalContainer}
|
||||
>
|
||||
{popoverHeader}
|
||||
<Command filter={filter}>
|
||||
<div className="flex min-h-11 items-center gap-1 px-2 pt-1">
|
||||
<div className="min-w-0 flex-1">
|
||||
@@ -328,6 +332,7 @@ function PillPopover({
|
||||
emptyMessage,
|
||||
portalContainer,
|
||||
action,
|
||||
popoverHeader,
|
||||
}: {
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
@@ -344,6 +349,7 @@ function PillPopover({
|
||||
emptyMessage: string;
|
||||
portalContainer: HTMLElement | null;
|
||||
action?: PillAction;
|
||||
popoverHeader?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
@@ -362,6 +368,7 @@ function PillPopover({
|
||||
emptyMessage={emptyMessage}
|
||||
portalContainer={portalContainer}
|
||||
action={action}
|
||||
popoverHeader={popoverHeader}
|
||||
/>
|
||||
</Popover>
|
||||
);
|
||||
@@ -383,6 +390,7 @@ type PillPopoverShellProps = {
|
||||
emptyMessage: string;
|
||||
portalContainer: HTMLElement | null;
|
||||
action?: PillAction;
|
||||
popoverHeader?: React.ReactNode;
|
||||
tooltip?: string;
|
||||
tooltipOpenState: boolean;
|
||||
suppressTooltip: boolean;
|
||||
@@ -407,6 +415,7 @@ function renderPillPopover({
|
||||
emptyMessage,
|
||||
portalContainer,
|
||||
action,
|
||||
popoverHeader,
|
||||
tooltip,
|
||||
tooltipOpenState,
|
||||
suppressTooltip,
|
||||
@@ -434,6 +443,7 @@ function renderPillPopover({
|
||||
emptyMessage={emptyMessage}
|
||||
portalContainer={portalContainer}
|
||||
action={action}
|
||||
popoverHeader={popoverHeader}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -539,6 +549,7 @@ export function Pill({
|
||||
tooltip,
|
||||
prefix,
|
||||
action,
|
||||
popoverHeader,
|
||||
}: PillProps) {
|
||||
const [open, setOpenState] = useState(false);
|
||||
const { tooltipOpenState, handleTooltipOpenChange, closeTooltip } = useTooltipMountGate();
|
||||
@@ -606,6 +617,7 @@ export function Pill({
|
||||
emptyMessage,
|
||||
portalContainer,
|
||||
action,
|
||||
popoverHeader,
|
||||
tooltip,
|
||||
tooltipOpenState,
|
||||
suppressTooltip,
|
||||
|
||||
@@ -215,6 +215,7 @@ export function RepoChipRepositoryPill({
|
||||
onCreateRepository,
|
||||
onRefreshRepositories,
|
||||
repositoriesRefreshing,
|
||||
popoverHeader,
|
||||
}: {
|
||||
repoLabel: string;
|
||||
repoTooltip: string;
|
||||
@@ -224,6 +225,7 @@ export function RepoChipRepositoryPill({
|
||||
onCreateRepository?: () => void;
|
||||
onRefreshRepositories?: () => void;
|
||||
repositoriesRefreshing?: boolean;
|
||||
popoverHeader?: React.ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
@@ -242,6 +244,7 @@ export function RepoChipRepositoryPill({
|
||||
onRefresh={onRefreshRepositories}
|
||||
refreshing={repositoriesRefreshing}
|
||||
refreshLabel="repositories"
|
||||
popoverHeader={popoverHeader}
|
||||
flat
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -32,6 +32,10 @@ vi.mock("./task-create-dialog-remote-repo-chip", () => ({
|
||||
selectedRemoteRepositoryIdentity: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("@/components/repository-discovery-controls", () => ({
|
||||
RepositoryDiscoveryControls: () => <div data-testid="repository-discovery-controls" />,
|
||||
}));
|
||||
|
||||
import { RepoChipsRow } from "./task-create-dialog-repo-chips";
|
||||
|
||||
afterEach(() => {
|
||||
@@ -100,6 +104,23 @@ const renderInProvider = (ui: Parameters<typeof render>[0]) =>
|
||||
render(<TooltipProvider>{ui}</TooltipProvider>);
|
||||
// eslint-disable-next-line max-lines-per-function -- test describe block, splitting hurts readability
|
||||
describe("RepoChipsRow", () => {
|
||||
it("mounts discovery controls only inside the open repository selector", () => {
|
||||
renderInProvider(
|
||||
<RepoChipsRow
|
||||
fs={makeFs({ repositories: [row({ key: "r0", repositoryId: REPO_FRONT_ID })] })}
|
||||
repositories={[makeRepo(REPO_FRONT_ID, "frontend")]}
|
||||
isTaskStarted={false}
|
||||
workspaceId="ws-1"
|
||||
onRowRepositoryChange={NOOP}
|
||||
onRowBranchChange={NOOP}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.queryByTestId("repository-discovery-controls")).toBeNull();
|
||||
fireEvent.click(screen.getByTestId(REPO_CHIP_TRIGGER));
|
||||
expect(screen.getByTestId("repository-discovery-controls")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("keeps the compact Repo, Remote, and None source-mode controls and test IDs", () => {
|
||||
const onToggleRemote = vi.fn();
|
||||
const onToggleNoRepository = vi.fn();
|
||||
|
||||
@@ -131,7 +131,6 @@ export function RepoChipsRow({
|
||||
// - "Fork a new branch" toggle is a separate flow that creates a NEW branch
|
||||
// from the selected base
|
||||
// Other executors: branch is fully editable (no special pre-fill).
|
||||
const branchLocked = false;
|
||||
// No early returns above hooks. URL mode and started-state checks happen below.
|
||||
if (isTaskStarted) return null;
|
||||
|
||||
@@ -157,7 +156,7 @@ export function RepoChipsRow({
|
||||
fs={fs}
|
||||
repositories={repositories}
|
||||
workspaceId={workspaceId}
|
||||
branchLocked={branchLocked}
|
||||
branchLocked={false}
|
||||
isLocalExecutor={!!isLocalExecutor}
|
||||
canAddMore={canAddMore}
|
||||
addHint={addHint}
|
||||
@@ -288,15 +287,8 @@ function ModeBody({
|
||||
onRefreshRepositories?: () => void;
|
||||
repositoriesRefreshing?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
if (fs.noRepository) {
|
||||
return (
|
||||
<FolderPicker
|
||||
value={fs.workspacePath}
|
||||
onChange={onWorkspacePathChange ?? (() => {})}
|
||||
placeholder={t("task:pickAStartingFolderOptional")}
|
||||
/>
|
||||
);
|
||||
return <NoRepositoryMode fs={fs} onWorkspacePathChange={onWorkspacePathChange} />;
|
||||
}
|
||||
if (fs.useRemote) {
|
||||
return (
|
||||
@@ -330,14 +322,14 @@ function ModeBody({
|
||||
onRowPolicyChange={onRowPolicyChange}
|
||||
onPolicySelected={onPolicySelected}
|
||||
showBranchPolicies
|
||||
showDiscoveryControls
|
||||
lastUsedBranch={lastUsedBranch}
|
||||
userSettingsLoaded={userSettingsLoaded}
|
||||
onCreateRepository={onCreateRepository}
|
||||
onRefreshRepositories={onRefreshRepositories}
|
||||
repositoriesRefreshing={repositoriesRefreshing}
|
||||
freshBranchToggle={
|
||||
// Multi-repo runs use worktrees, so the existing-vs-fork choice
|
||||
// is irrelevant — only surface the toggle for single-repo flows.
|
||||
// Multi-repo worktrees do not need the existing-vs-fork choice.
|
||||
freshBranchAvailable && onToggleFreshBranch && fs.repositories.length === 1 ? (
|
||||
<FreshBranchToggle enabled={!!freshBranchEnabled} onToggle={onToggleFreshBranch} />
|
||||
) : null
|
||||
@@ -346,6 +338,23 @@ function ModeBody({
|
||||
);
|
||||
}
|
||||
|
||||
function NoRepositoryMode({
|
||||
fs,
|
||||
onWorkspacePathChange,
|
||||
}: {
|
||||
fs: DialogFormState;
|
||||
onWorkspacePathChange?: (value: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<FolderPicker
|
||||
value={fs.workspacePath}
|
||||
onChange={onWorkspacePathChange ?? (() => {})}
|
||||
placeholder={t("task:pickAStartingFolderOptional")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FreshBranchToggle({
|
||||
enabled,
|
||||
onToggle,
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
} from "@/components/task-create-dialog-repo-chip-parts";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { t } from "@/lib/i18n";
|
||||
import { RepositoryDiscoveryControls } from "@/components/repository-discovery-controls";
|
||||
|
||||
type WorkspaceRepoChipsProps = {
|
||||
rows: TaskRepoRow[];
|
||||
@@ -36,6 +37,7 @@ type WorkspaceRepoChipsProps = {
|
||||
freshBranchEnabled?: boolean;
|
||||
branchPolicyDisabledReason?: string;
|
||||
showBranchPolicies?: boolean;
|
||||
showDiscoveryControls?: boolean;
|
||||
canAddMore: boolean;
|
||||
addHint?: string;
|
||||
addLabel?: string;
|
||||
@@ -71,6 +73,7 @@ export function WorkspaceRepoChips({
|
||||
freshBranchEnabled,
|
||||
branchPolicyDisabledReason,
|
||||
showBranchPolicies = false,
|
||||
showDiscoveryControls = false,
|
||||
canAddMore,
|
||||
addHint,
|
||||
addLabel,
|
||||
@@ -127,6 +130,7 @@ export function WorkspaceRepoChips({
|
||||
}
|
||||
onPolicySelected={onPolicySelected}
|
||||
showBranchPolicies={showBranchPolicies}
|
||||
showDiscoveryControls={showDiscoveryControls}
|
||||
onCreateRepository={
|
||||
rows.length === 1 && onCreateRepository ? () => onCreateRepository(row.key) : undefined
|
||||
}
|
||||
@@ -263,6 +267,7 @@ type RepoChipProps = {
|
||||
onPolicySelected?: () => void;
|
||||
branchPolicyDisabledReason?: string;
|
||||
showBranchPolicies?: boolean;
|
||||
showDiscoveryControls?: boolean;
|
||||
onRemove: () => void;
|
||||
onCreateRepository?: () => void;
|
||||
onRefreshRepositories?: () => void;
|
||||
@@ -479,6 +484,8 @@ function RepoChipContent({
|
||||
onCreateRepository,
|
||||
onRefreshRepositories,
|
||||
repositoriesRefreshing,
|
||||
showDiscoveryControls,
|
||||
workspaceId,
|
||||
}: RepoChipProps & { data: RepoChipData; branchPolicies: RepositoryBranchPolicy[] }) {
|
||||
const { repoOptions, branchOptions, branches, branchesLoading, refreshBranches } = data;
|
||||
const { repoLabel, repoTooltip } = computeRepoChipDisplay(
|
||||
@@ -514,6 +521,11 @@ function RepoChipContent({
|
||||
onCreateRepository={onCreateRepository}
|
||||
onRefreshRepositories={onRefreshRepositories}
|
||||
repositoriesRefreshing={repositoriesRefreshing}
|
||||
popoverHeader={
|
||||
showDiscoveryControls ? (
|
||||
<RepositoryDiscoveryControls workspaceId={workspaceId} presentation="picker" />
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
<RepoChipBranchPill
|
||||
branchPicker={branchPicker}
|
||||
|
||||
+43
-6
@@ -5,16 +5,26 @@ import { AddWorkspaceSourcesDialog } from "./add-workspace-sources-dialog";
|
||||
import { StateProvider, useAppStore, useAppStoreApi } from "@/components/state-provider";
|
||||
import { sessionId as toSessionId, taskId as toTaskId } from "@/lib/types/http";
|
||||
import { TooltipProvider } from "@kandev/ui/tooltip";
|
||||
import { repositoryDiscoveryCoordinator } from "@/hooks/domains/workspace/use-repository-discovery";
|
||||
|
||||
let isMobile = false;
|
||||
const ADD_SOURCES_LABEL = "Add sources";
|
||||
const { attachTaskWorkspaceSources, discoverRepositoriesAction, refreshRepositories } = vi.hoisted(
|
||||
() => ({
|
||||
const {
|
||||
attachTaskWorkspaceSources,
|
||||
discoverRepositoriesAction,
|
||||
getRepositoryDiscoveryAction,
|
||||
refreshRepositoryDiscoveryAction,
|
||||
refreshRepositories,
|
||||
} = vi.hoisted(() => {
|
||||
const discover = vi.fn().mockResolvedValue({ repositories: [] });
|
||||
return {
|
||||
attachTaskWorkspaceSources: vi.fn(),
|
||||
discoverRepositoriesAction: vi.fn().mockResolvedValue({ repositories: [] }),
|
||||
discoverRepositoriesAction: discover,
|
||||
getRepositoryDiscoveryAction: discover,
|
||||
refreshRepositoryDiscoveryAction: discover,
|
||||
refreshRepositories: vi.fn().mockResolvedValue(undefined),
|
||||
}),
|
||||
);
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/hooks/use-responsive-breakpoint", () => ({
|
||||
useResponsiveBreakpoint: () => ({ isMobile }),
|
||||
@@ -33,8 +43,16 @@ vi.mock("@/components/folder-picker", () => ({
|
||||
</button>
|
||||
),
|
||||
}));
|
||||
vi.mock("@/components/repository-discovery-controls", () => ({
|
||||
RepositoryDiscoveryControls: ({ enabled }: { enabled?: boolean }) =>
|
||||
enabled !== false ? <div data-testid="repository-discovery-controls" /> : null,
|
||||
}));
|
||||
vi.mock("@/lib/api/domains/kanban-api", () => ({ attachTaskWorkspaceSources }));
|
||||
vi.mock("@/app/actions/workspaces", () => ({ discoverRepositoriesAction }));
|
||||
vi.mock("@/app/actions/workspaces", () => ({
|
||||
discoverRepositoriesAction,
|
||||
getRepositoryDiscoveryAction,
|
||||
refreshRepositoryDiscoveryAction,
|
||||
}));
|
||||
|
||||
async function finishClose(surface: HTMLElement, isDrawer: boolean) {
|
||||
await waitFor(() => expect(surface.getAttribute("data-state")).not.toBe("open"));
|
||||
@@ -110,6 +128,7 @@ function HarnessContent({
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
repositoryDiscoveryCoordinator.dispose();
|
||||
isMobile = false;
|
||||
attachTaskWorkspaceSources.mockReset();
|
||||
discoverRepositoriesAction.mockClear();
|
||||
@@ -164,6 +183,24 @@ describe("AddWorkspaceSourcesDialog consequences", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("AddWorkspaceSourcesDialog repository discovery", () => {
|
||||
it("mounts discovery controls only inside a saved repository selector", async () => {
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<Harness />
|
||||
</TooltipProvider>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: ADD_SOURCES_LABEL }));
|
||||
expect(screen.queryByTestId("repository-discovery-controls")).toBeNull();
|
||||
openRepositoryMenu();
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Workspace repository" }));
|
||||
fireEvent.click(screen.getByTestId("repo-chip-trigger"));
|
||||
|
||||
expect(screen.getByTestId("repository-discovery-controls")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("AddWorkspaceSourcesDialog", () => {
|
||||
it("uses a touch-sized repository menu without tabs or discarded mixed source rows", async () => {
|
||||
isMobile = true;
|
||||
|
||||
@@ -75,6 +75,7 @@ export function SavedRepositorySourceRow({
|
||||
repositories={repositories}
|
||||
discoveredRepositories={discoveredRepositories}
|
||||
workspaceId={workspaceId}
|
||||
showDiscoveryControls
|
||||
canAddMore={false}
|
||||
onAdd={() => {}}
|
||||
onRemove={() => {}}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { discoverRepositoriesAction } from "@/app/actions/workspaces";
|
||||
import { useCallback } from "react";
|
||||
import { useRepositories } from "@/hooks/domains/workspace/use-repositories";
|
||||
import type { LocalRepository } from "@/lib/types/http";
|
||||
import { useRepositoryDiscovery } from "@/hooks/domains/workspace/use-repository-discovery";
|
||||
|
||||
export function useWorkspaceRepositoryOptions(workspaceId: string | null, open: boolean) {
|
||||
const {
|
||||
@@ -11,46 +10,16 @@ export function useWorkspaceRepositoryOptions(workspaceId: string | null, open:
|
||||
isLoading: repositoriesLoading,
|
||||
refresh: refreshRepositories,
|
||||
} = useRepositories(workspaceId, open);
|
||||
const [discoveredRepositories, setDiscoveredRepositories] = useState<LocalRepository[]>([]);
|
||||
const [repositoriesDiscovering, setRepositoriesDiscovering] = useState(false);
|
||||
const currentWorkspaceRef = useRef(workspaceId);
|
||||
currentWorkspaceRef.current = workspaceId;
|
||||
|
||||
const discoverRepositories = useCallback(async () => {
|
||||
if (!workspaceId) {
|
||||
setDiscoveredRepositories([]);
|
||||
return;
|
||||
}
|
||||
const requestedWorkspaceId = workspaceId;
|
||||
setRepositoriesDiscovering(true);
|
||||
try {
|
||||
const result = await discoverRepositoriesAction(requestedWorkspaceId);
|
||||
if (currentWorkspaceRef.current === requestedWorkspaceId) {
|
||||
setDiscoveredRepositories(result.repositories);
|
||||
}
|
||||
} catch {
|
||||
if (currentWorkspaceRef.current === requestedWorkspaceId) {
|
||||
setDiscoveredRepositories([]);
|
||||
}
|
||||
} finally {
|
||||
if (currentWorkspaceRef.current === requestedWorkspaceId) {
|
||||
setRepositoriesDiscovering(false);
|
||||
}
|
||||
}
|
||||
}, [workspaceId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) void discoverRepositories();
|
||||
}, [discoverRepositories, open]);
|
||||
const discovery = useRepositoryDiscovery(workspaceId, open);
|
||||
|
||||
const refreshRepositoryOptions = useCallback(() => {
|
||||
void Promise.all([refreshRepositories(), discoverRepositories()]);
|
||||
}, [discoverRepositories, refreshRepositories]);
|
||||
void Promise.all([refreshRepositories(), discovery.refresh()]);
|
||||
}, [discovery.refresh, refreshRepositories]);
|
||||
|
||||
return {
|
||||
repositories,
|
||||
discoveredRepositories,
|
||||
repositoriesRefreshing: repositoriesLoading || repositoriesDiscovering,
|
||||
discoveredRepositories: discovery.repositories,
|
||||
repositoriesRefreshing: repositoriesLoading || discovery.isLoading || discovery.isRefreshing,
|
||||
refreshRepositoryOptions,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { expect, test } from "../../fixtures/test-base";
|
||||
import { useRegularMode } from "../../helpers/regular-mode";
|
||||
import { waitForFiniteAnimations } from "../../helpers/animations";
|
||||
import { MobileKanbanPage } from "../../pages/mobile-kanban-page";
|
||||
import fs from "node:fs";
|
||||
|
||||
useRegularMode();
|
||||
|
||||
test.describe("Mobile repository discovery consent", () => {
|
||||
test("shows discovery actions only inside the repository selector with matched touch targets", async ({
|
||||
testPage,
|
||||
backend,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
await backend.restart({ KANDEV_DESKTOP_RUNTIME: "true" });
|
||||
const mobile = new MobileKanbanPage(testPage);
|
||||
await mobile.goto();
|
||||
await mobile.mobileFab.tap();
|
||||
|
||||
const dialog = testPage.getByTestId("create-task-dialog");
|
||||
await expect(dialog).toBeVisible();
|
||||
await expect(dialog.getByTestId("discovery-root-controls")).toHaveCount(0);
|
||||
|
||||
await dialog.getByTestId("repo-chip-trigger").first().tap();
|
||||
const controls = testPage.getByTestId("discovery-root-controls");
|
||||
const chooseFolders = controls.getByTestId("folder-picker-trigger");
|
||||
const refreshRepositories = controls.getByRole("button", {
|
||||
name: "Refresh repositories",
|
||||
});
|
||||
await expect(controls).toBeVisible();
|
||||
await waitForFiniteAnimations(controls);
|
||||
|
||||
const [chooseBox, refreshBox] = await Promise.all([
|
||||
chooseFolders.boundingBox(),
|
||||
refreshRepositories.boundingBox(),
|
||||
]);
|
||||
const [chooseCssHeight, refreshCssHeight] = await Promise.all([
|
||||
chooseFolders.evaluate((element) => Number.parseFloat(getComputedStyle(element).height)),
|
||||
refreshRepositories.evaluate((element) =>
|
||||
Number.parseFloat(getComputedStyle(element).height),
|
||||
),
|
||||
]);
|
||||
expect(chooseBox).not.toBeNull();
|
||||
expect(refreshBox).not.toBeNull();
|
||||
expect(refreshBox!.height).toBeCloseTo(chooseBox!.height, 1);
|
||||
expect(chooseCssHeight).toBe(44);
|
||||
expect(refreshCssHeight).toBe(44);
|
||||
});
|
||||
|
||||
test("uses the HTTP picker on a mobile browser connected to a desktop backend", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
backend,
|
||||
seedData,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const homePath = fs.realpathSync(backend.tmpDir);
|
||||
let rootSaved = false;
|
||||
|
||||
try {
|
||||
await backend.restart({ KANDEV_DESKTOP_RUNTIME: "true" });
|
||||
await testPage.setViewportSize({ width: 390, height: 844 });
|
||||
await testPage.goto(`/settings/workspaces/${seedData.workspaceId}/repositories`);
|
||||
await testPage.getByRole("button", { name: "Add Local Repository" }).click();
|
||||
|
||||
const dialog = testPage.getByRole("dialog", { name: "Add Local Repository" });
|
||||
const controls = dialog.getByTestId("discovery-root-controls");
|
||||
await expect(controls).toBeVisible();
|
||||
|
||||
const listingResponse = testPage.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes("/api/v1/fs/list-dir") &&
|
||||
response.request().method() === "GET" &&
|
||||
response.ok(),
|
||||
);
|
||||
await controls.getByTestId("folder-picker-trigger").tap();
|
||||
await listingResponse;
|
||||
const picker = testPage.getByTestId("folder-picker-popover");
|
||||
await expect(picker).toBeVisible();
|
||||
await expect(picker.getByTestId("folder-picker-choose")).toBeEnabled();
|
||||
|
||||
const addResponse = testPage.waitForResponse(
|
||||
(response) =>
|
||||
response.url().endsWith("/api/v1/repositories/discovery/roots") &&
|
||||
response.request().method() === "POST" &&
|
||||
response.ok(),
|
||||
);
|
||||
await picker.getByTestId("folder-picker-choose").tap();
|
||||
expect((await addResponse).status()).toBe(201);
|
||||
rootSaved = true;
|
||||
|
||||
await expect(controls.getByRole("button", { name: "Refresh repositories" })).toBeVisible();
|
||||
expect(
|
||||
await testPage.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth),
|
||||
).toBe(true);
|
||||
} finally {
|
||||
if (rootSaved) {
|
||||
await apiClient
|
||||
.rawRequest(
|
||||
"DELETE",
|
||||
`/api/v1/repositories/discovery/roots?path=${encodeURIComponent(homePath)}`,
|
||||
)
|
||||
.catch(() => undefined);
|
||||
}
|
||||
await backend.restart();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
import { expect, test } from "../../fixtures/test-base";
|
||||
import { useRegularMode } from "../../helpers/regular-mode";
|
||||
import { waitForFiniteAnimations } from "../../helpers/animations";
|
||||
import { KanbanPage } from "../../pages/kanban-page";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
useRegularMode();
|
||||
|
||||
test.describe("Desktop repository discovery consent", () => {
|
||||
test("shows compact discovery actions only inside the repository selector", async ({
|
||||
testPage,
|
||||
backend,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
await backend.restart({ KANDEV_DESKTOP_RUNTIME: "true" });
|
||||
const kanban = new KanbanPage(testPage);
|
||||
await kanban.goto();
|
||||
await kanban.createTaskButton.first().click();
|
||||
|
||||
const dialog = testPage.getByTestId("create-task-dialog");
|
||||
await expect(dialog).toBeVisible();
|
||||
await expect(dialog.getByTestId("discovery-root-controls")).toHaveCount(0);
|
||||
|
||||
await dialog.getByTestId("repo-chip-trigger").first().click();
|
||||
const controls = testPage.getByTestId("discovery-root-controls");
|
||||
const chooseFolders = controls.getByTestId("folder-picker-trigger");
|
||||
const refreshRepositories = controls.getByRole("button", {
|
||||
name: "Refresh repositories",
|
||||
});
|
||||
await expect(controls).toBeVisible();
|
||||
await waitForFiniteAnimations(controls);
|
||||
|
||||
const [chooseBox, refreshBox] = await Promise.all([
|
||||
chooseFolders.boundingBox(),
|
||||
refreshRepositories.boundingBox(),
|
||||
]);
|
||||
expect(chooseBox).not.toBeNull();
|
||||
expect(refreshBox).not.toBeNull();
|
||||
expect(refreshBox!.height).toBeCloseTo(chooseBox!.height, 1);
|
||||
expect(refreshBox!.height).toBeLessThanOrEqual(32);
|
||||
});
|
||||
|
||||
test("uses the native picker and keeps the discovery root recoverable", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
backend,
|
||||
seedData,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const selectedRoot = fs.mkdtempSync(path.join(backend.tmpDir, "desktop-discovery-root-"));
|
||||
let rootSaved = false;
|
||||
let directoryListingRequests = 0;
|
||||
const onRequest = (request: { url(): string; method(): string }) => {
|
||||
if (request.url().includes("/api/v1/fs/list-dir") && request.method() === "GET") {
|
||||
directoryListingRequests += 1;
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
await backend.restart({ KANDEV_DESKTOP_RUNTIME: "true" });
|
||||
await testPage.addInitScript(
|
||||
({ selectedPath }: { selectedPath: string }) => {
|
||||
const win = window as typeof window & {
|
||||
__TAURI_INTERNALS__?: {
|
||||
invoke: (command: string, args?: Record<string, unknown>) => Promise<unknown>;
|
||||
transformCallback: () => number;
|
||||
};
|
||||
__kandevFolderPickerCommands?: string[];
|
||||
};
|
||||
const commands: string[] = [];
|
||||
win.__kandevFolderPickerCommands = commands;
|
||||
Object.defineProperty(win, "__TAURI_INTERNALS__", {
|
||||
configurable: true,
|
||||
value: {
|
||||
transformCallback: () => 1,
|
||||
invoke: async (command: string) => {
|
||||
commands.push(command);
|
||||
if (command === "pick_directory") {
|
||||
return { status: "selected", path: selectedPath };
|
||||
}
|
||||
if (command === "plugin:event|listen") return 1;
|
||||
if (command === "get_native_notification_permission") return "granted";
|
||||
if (command === "request_native_notification_permission") return "granted";
|
||||
if (command === "get_update_state") {
|
||||
return {
|
||||
phase: "idle",
|
||||
currentVersion: "",
|
||||
latestVersion: null,
|
||||
releaseNotes: null,
|
||||
releaseUrl: null,
|
||||
checkedAtEpochMs: null,
|
||||
downloadedBytes: null,
|
||||
totalBytes: null,
|
||||
installSupported: false,
|
||||
installUnsupportedReason: null,
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
{ selectedPath: selectedRoot },
|
||||
);
|
||||
testPage.on("request", onRequest);
|
||||
|
||||
await testPage.goto(`/settings/workspaces/${seedData.workspaceId}/repositories`);
|
||||
await testPage.getByRole("button", { name: "Add Local Repository" }).click();
|
||||
const dialog = testPage.getByRole("dialog", { name: "Add Local Repository" });
|
||||
const controls = dialog.getByTestId("discovery-root-controls");
|
||||
await expect(controls).toBeVisible();
|
||||
|
||||
const addResponse = testPage.waitForResponse(
|
||||
(response) =>
|
||||
response.url().endsWith("/api/v1/repositories/discovery/roots") &&
|
||||
response.request().method() === "POST" &&
|
||||
response.ok(),
|
||||
);
|
||||
await controls
|
||||
.getByRole("button", { name: "Choose folders to discover repositories" })
|
||||
.click();
|
||||
expect((await addResponse).status()).toBe(201);
|
||||
rootSaved = true;
|
||||
|
||||
await expect(controls.getByTitle(selectedRoot)).toBeVisible();
|
||||
expect(
|
||||
await testPage.evaluate(
|
||||
() =>
|
||||
(window as typeof window & { __kandevFolderPickerCommands?: string[] })
|
||||
.__kandevFolderPickerCommands ?? [],
|
||||
),
|
||||
).toContain("pick_directory");
|
||||
expect(directoryListingRequests).toBe(0);
|
||||
|
||||
const refreshResponse = testPage.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes("/api/v1/workspaces/") &&
|
||||
response.url().includes("/repositories/discovery/refresh") &&
|
||||
response.request().method() === "POST" &&
|
||||
response.ok(),
|
||||
);
|
||||
await controls.getByRole("button", { name: "Refresh repositories" }).click();
|
||||
await refreshResponse;
|
||||
|
||||
const removeResponse = testPage.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes("/api/v1/repositories/discovery/roots?") &&
|
||||
response.request().method() === "DELETE" &&
|
||||
response.ok(),
|
||||
);
|
||||
await controls.getByRole("button", { name: "Remove" }).click();
|
||||
await removeResponse;
|
||||
rootSaved = false;
|
||||
await expect(controls.getByTitle(selectedRoot)).toHaveCount(0);
|
||||
} finally {
|
||||
testPage.off("request", onRequest);
|
||||
if (rootSaved) {
|
||||
await apiClient
|
||||
.rawRequest(
|
||||
"DELETE",
|
||||
`/api/v1/repositories/discovery/roots?path=${encodeURIComponent(selectedRoot)}`,
|
||||
)
|
||||
.catch(() => undefined);
|
||||
}
|
||||
fs.rmSync(selectedRoot, { recursive: true, force: true });
|
||||
await backend.restart();
|
||||
}
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user