OUTPUT #918 | 3012 karakter | 70 satır
========== YENİ KOMUT | 21.09.2026 21:00:39 ==========

 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/Error'
 *       429:
 *         description: Tab limit reached.
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/Error'
 *       409:
 *         description: Cannot enable tracing on an existing session.
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/Error'
 */
app.post('/tabs', async (req, res) => {
  try {
    const { userId, sessionKey, listItemId, url, trace } = req.body;
    // Accept both sessionKey (preferred) and listItemId (legacy) for backward compatibility
    const resolvedSessionKey = sessionKey || listItemId;
    if (!userId || !resolvedSessionKey) {
      return res.status(400).json({ error: 'userId and sessionKey required' });
    }

    // Session overflow redirect (Fly.io only) — if this machine is above its
    // fair share of sessions and the user doesn't already have one here,
    // bounce back through the Fly Proxy to land on a less-loaded machine.
    if (FLY_MACHINE_ID) {
      const PER_MACHINE_SESSION_CAP = Math.max(3, Math.ceil(MAX_SESSIONS / 3));
      const key = normalizeUserId(userId);
      const isReplayed = !!req.headers['fly-replay-src'];
      if (sessions.size >= PER_MACHINE_SESSION_CAP && !sessions.has(key) && !isReplayed) {
        log('info', 'session overflow redirect', {
          userId: key, sessions: sessions.size, cap: PER_MACHINE_SESSION_CAP,
        });
        res.set('fly-replay', `app=${CONFIG.flyAppName || 'camofox-browser'}`);
        return res.status(307).send();
      }
    }

    const result = await withTimeout((async () => {
      const existing = sessions.get(normalizeUserId(userId));
      if (trace && existing && !existing.tracePath) {
        throw Object.assign(
          new Error('trace must be set on session creation. DELETE /sessions/:userId first to restart with tracing.'),
          { statusCode: 409 },
        );
      }
      let session = await getSession(userId, { trace: !!trace });

      let totalTabs = 0;
      for (const group of session.tabGroups.values()) totalTabs += group.size;

      // Recycle oldest tab when limits are reached instead of rejecting
      if (totalTabs >= MAX_TABS_PER_SESSION || getTotalTabCount() >= MAX_TABS_GLOBAL) {
        const recycled = await recycleOldestTab(session, req.reqId, userId);
        if (!recycled) {
          throw Object.assign(new Error('Maximum tabs per session reached'), { statusCode: 429 });
        }
      }

      const createdPage = await createPageWithRecoveryForUser(userId, session, { trace: !!trace });
      session = createdPage.session;
      const page = createdPage.page;
      const lease = createdPage.lease;
root@213-238-170-219:/home/hermes/.hermes/hermes-agent#