Skip to content

Feature: Resume most recent session instead of always creating a new one #63

Description

@clytn3128

Problem

When opening the OpenCode panel in Obsidian, ensureSessionUrl() always calls createSession(), which creates a new session every time. This means users lose context from their previous conversations and have to manually navigate to their old session.

Proposed Solution

Before creating a new session, query existing sessions via GET /session API and resume the most recently updated one. Only create a new session if no existing sessions are found.

Suggested Implementation

1. Add listSessions() method to the client class

async listSessions() {
  const result = await this.request("GET", "/session");
  const sessions = this.unwrap(result);
  if (!sessions || !Array.isArray(sessions) || sessions.length === 0) {
    return [];
  }
  return sessions.sort((a, b) => {
    const ta = a.updatedAt || a.createdAt || "";
    const tb = b.updatedAt || b.createdAt || "";
    return tb.localeCompare(ta);
  });
}

2. Modify ensureSessionUrl() logic

async ensureSessionUrl(view) {
  if (this.getServerState() !== "running") {
    return;
  }
  const cachedUrl = this.getCachedIframeUrl();
  const existingUrl = cachedUrl != null ? cachedUrl : view.getIframeUrl();
  if (existingUrl && this.client.resolveSessionId(existingUrl)) {
    this.setCachedIframeUrl(existingUrl);
    return;
  }
  let sessionId = null;
  try {
    const sessions = await this.client.listSessions();
    if (sessions.length > 0) {
      sessionId = sessions[0].id;
      console.log("[OpenCode] Resuming existing session:", sessionId);
    }
  } catch (e) {
    console.log("[OpenCode] Could not list sessions, creating new one");
  }
  if (!sessionId) {
    sessionId = await this.client.createSession();
  }
  if (!sessionId) {
    return;
  }
  const sessionUrl = this.client.getSessionUrl(sessionId);
  this.setCachedIframeUrl(sessionUrl);
  view.setIframeUrl(sessionUrl);
  if (this.app.workspace.activeLeaf === view.leaf) {
    await this.contextManager.refreshContextForView(view);
  }
}

Alternative Considerations

  • Could add a setting to let users choose between "always new session" and "resume latest session"
  • Could add a "New Session" button in the panel header for when users explicitly want a fresh start

I've tested this modification locally and it works well — the panel now resumes the most recent session on startup.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions