Qwen Code Long Sessions: Compression, Auto-Compact, and Context Settings

When a Qwen Code session approaches its context limit, do not clear it or inflate the window setting first. Preserve code and task state, choose summary-based or fast compression, verify continuity, then place autoCompactThreshold and contextWindowSize at the configuration level that actually applies.

Contents
Qwen Code Long Sessions: Compression, Auto-Compact, and Context Settings

When a long Qwen Code session is nearly full, do not start with /clear, and do not raise contextWindowSize to an arbitrary larger number. The safer order is: confirm that the problem is context capacity rather than account quota, preserve the code and task state, choose the right compression method, verify the result, and only then correct the automatic threshold and model-window configuration.

The commands and settings below reflect the Qwen Code command documentation, settings reference, and Model Providers reference opened on October 11, 2026. Commands can differ by installed version, so begin with the version you actually run rather than an old configuration copied from another machine.

First decide whether the problem is context or quota

Both can interrupt a long task, but they require different fixes.

SymptomMore likely causeNext action
/context shows high usage, or a request says the context is too longThe current session is near its context capacitySave the task state, then compress
The provider reports credits, balance, subscription, rate, or account limitsAccount or API quotaCheck the provider console; compression does not add quota
/context reports a total window that is implausibly high or lowQwen Code is assuming the wrong model windowCorrect the value and placement of contextWindowSize
Usage drops after compression, but the next call still reports insufficient quotaIt is not a context problemCheck the account, key, plan, balance, and rate limit

contextWindowSize tells Qwen Code what window to assume for estimates and compaction triggers. It does not enlarge the model or API service’s real limit, and it does not restore a subscription or API balance.

Check the installed version and current usage

Run these commands before changing the session:

/status
/help
/model
/doctor
/context detail

Wait for each command to finish and return control to the prompt. Use /status for the version, /model to inspect the current model selection, /doctor for authentication and environment checks, and /context detail for the context breakdown.

If /summary, /compress-fast, or a setting used below is absent from your build, consult the official Qwen Code installation instructions before troubleshooting the setting. Repeatedly changing a key that the installed version does not support will not help.

Preserve two kinds of state before compression

Compression changes conversation history. It does not save uncommitted code for you, and no generated summary is guaranteed to retain every implicit constraint. Keep a code checkpoint and a task checkpoint.

Preserve the code state

In a Git project, run:

!git status --short
!git diff --stat

Inspect the full diff when necessary, or create a checkpoint commit you are willing to keep. At minimum, know which files changed, which files are untracked, and which tests have not run.

Preserve the task state

Ask the current session to produce an explicit handoff before it edits anything else:

Without changing files, write a task checkpoint containing:
- final goal
- completed work
- changed files and key edits
- constraints that must not change
- verification already run and its results
- unresolved problems
- the single next action and its verification command

After checking that the handoff is complete, run:

/summary

Without a custom path, the documented destination is:

.qwen/PROJECT_SUMMARY.md

/summary is non-destructive: it writes a project summary without replacing the current chat history. Re-inject the file for a read-only audit:

@.qwen/PROJECT_SUMMARY.md Check the goal, constraints, changed files, verification results, and next step. Report omissions only; do not edit code.

Keep the default path when you rely on Qwen Code’s welcome-back flow. The command documentation says that summaries saved to a custom path are not discovered by that flow.

Choose /compress, /compress-fast, /summary, or /clear

CommandWhat it doesBest fitMain risk
/summaryWrites project state to a file without replacing historyBefore a real compaction, before stopping for the day, or before a new sessionThe generated checkpoint still needs review
/compressReplaces chat history with a summary to free contextTasks with many decisions, constraints, and dependenciesIt is destructive to chat history, and details can be omitted
/compress-fastUses no AI and removes older tool output and thinking contentTool-heavy sessions whose active goal is already explicitRemoved older tool output may contain information needed later; record and verify it in the checkpoint first
/clearClears conversation history and frees contextYou intentionally abandon the old conversation and will restart from external stateThe previous conversational context is removed

For most long coding tasks, use this sequence: run /summary, review the file, then run /compress. Use /compress-fast when normal compaction cannot complete, provider calls are temporarily unavailable, or stale logs and tool output dominate the session and the task state is already saved.

Do not confuse /summarize with the file-saving command. The current documentation defines /summarize as an alias for /compress, so it also replaces chat history.

A verifiable long-session compression workflow

1. Prepare the input

Confirm that you have saved:

  • the active goal and non-negotiable constraints;
  • changed files and Git state;
  • completed and pending verification;
  • the next action and its success condition;
  • a reviewed .qwen/PROJECT_SUMMARY.md.

2. Run the compression

For a complex task, run:

/compress

For a tool-output-heavy session with an explicit checkpoint, run:

/compress-fast

Run one compression command at a time. Wait until it completes and the input prompt returns before sending new code-editing instructions.

3. Retain the outputs

Keep two outputs:

  1. .qwen/PROJECT_SUMMARY.md, which stores the task checkpoint;
  2. the working tree and Git diff, which store the actual code changes.

The compressed conversation is not the only source of truth. The filesystem, test output, and diff determine what actually changed.

4. Verify success

Run:

/context

Context usage should be materially lower. Then send a read-only continuity check:

Do not change files yet. Answer:
1. What is the single current goal?
2. Which constraints must not change?
3. Which files have been modified?
4. Which checks passed, and which have not run?
5. What is the single next action and its success signal?

Compare the answer with .qwen/PROJECT_SUMMARY.md, git status, and the actual test record. Once all three agree, execute one small next step and run the most relevant verification. Avoid asking the model to refactor several modules immediately after compaction.

5. Handle failure without losing the task

  • If /compress fails after the checkpoint is saved, try /compress-fast. If that also fails, start a new session and inject @.qwen/PROJECT_SUMMARY.md.
  • If constraints are missing after compaction, re-inject the summary, correct the omissions, and ask for the checkpoint to be restated before allowing edits.
  • If context usage falls but the next request still fails, inspect whether the provider error refers to balance, subscription, rate limits, or authentication. Those are not fixed by compression.
  • If the service still rejects the request for excessive context, check whether contextWindowSize is larger than the provider’s effective limit.

Fix the automatic threshold: the old key no longer applies

The current key is:

{
  "context": {
    "autoCompactThreshold": 0.85
  }
}

The valid range is greater than 0 and no more than 1; the default is 0.85. It is a ceiling, not a promise that every model compacts at exactly 85 percent. Smaller windows can compact earlier to leave room for the generated summary.

The removed and silently ignored path is model.chatCompression.contextPercentageThreshold:

{
  "model": {
    "chatCompression": {
      "contextPercentageThreshold": 0.7
    }
  }
}

When migrating an old configuration, first move the value to context.autoCompactThreshold and observe the default 0.85. Lower it only after confirming that compaction repeatedly occurs too late for your workload. Do not raise it simply to postpone compaction.

Put the threshold at user or project scope deliberately

The two common persistent locations are:

  • ~/.qwen/settings.json: applies to all projects for the current user;
  • .qwen/settings.json in the project root: applies only to that project and overrides user settings.

Use user scope when the same provider and behavior apply everywhere. Use project scope when a repository has a different provider, effective window, or compaction policy.

Higher-precedence sources can still win. The documented order is defaults, system defaults, user settings, project settings, system settings, environment variables, then command-line arguments. If editing the user file appears to do nothing, inspect the project file, system policy, and launch arguments.

/config can read and write simple settings, for example:

/config context.autoCompactThreshold=0.85

However, the command documentation states that /config writes to ~/.qwen/settings.json. Edit .qwen/settings.json directly when the value must be project-specific.

You can catch JSON syntax errors before relaunching:

!python3 -m json.tool ~/.qwen/settings.json >/dev/null
!python3 -m json.tool .qwen/settings.json >/dev/null

Run the second command only when the project file exists.

Put contextWindowSize in the configuration layer that is actually used

Set contextWindowSize to the provider’s effective limit for the selected model, not a marketing maximum and not the number you wish the service supported. A value that is too high causes late compaction; a value that is too low causes premature warnings and compaction.

A model selected from modelProviders

In this case, put the value inside the matching provider entry. The 128000 below is only a structural example and must be replaced with the provider’s current effective limit:

{
  "modelProviders": {
    "openai": [
      {
        "id": "your-model-id",
        "name": "Your model",
        "baseUrl": "https://provider.example/v1",
        "envKey": "OPENAI_API_KEY",
        "generationConfig": {
          "contextWindowSize": 128000
        }
      }
    ]
  },
  "security": {
    "auth": {
      "selectedType": "openai"
    }
  },
  "model": {
    "name": "your-model-id"
  }
}

Provider model entries are sealed: top-level model.generationConfig does not fill their missing fields. The same placement rule applies to any OpenAI-compatible custom endpoint—for example, BetterToken as one possible API service—after you verify support for the client, resource, and selected model.

A runtime model not selected from modelProviders

Only when the active model does not come from a provider entry should you use the top-level setting:

{
  "model": {
    "generationConfig": {
      "contextWindowSize": 128000
    }
  }
}

Do not set conflicting values at both levels and guess which one wins. Inspect the current model with /model, check authentication with /doctor, identify how the model was selected, and use one correct location.

Troubleshoot in this order

SymptomLikely causeFix and verification
/compress-fast is unknownThe installed build is olderRun /status, update using official instructions, then confirm with /help
The old threshold changes nothingThe legacy key is silently ignoredMove it to context.autoCompactThreshold and inspect the effective configuration
Editing user settings changes nothingProject or system configuration overrides itInspect .qwen/settings.json, system settings, and launch arguments
A 0.85 setting compacts earlierA smaller window needs summary headroomThis can be expected; inspect the actual window and usage with /context
/context reports an unrealistically large windowcontextWindowSize is wrong or at the wrong levelPut the effective provider limit in the selected provider’s generationConfig
The server still reports context overflowThe configured limit exceeds the service’s real limitReduce it to the effective limit, reopen the session, and verify again
Quota errors remain after successful compactionAccount balance, subscription, or rate limitingCheck the provider console rather than changing context settings
The model cannot state the next stepThe checkpoint was incomplete or the summary omitted detailsInject PROJECT_SUMMARY.md, compare Git and test records, then continue

Four rules to keep

  1. Separate context from quota. Compression reduces session context; it does not add account capacity.
  2. Save before compressing. Git protects code state; /summary protects task state.
  3. Use /compress for complex continuity and /compress-fast for tool-output bloat. Verify after either one.
  4. Place settings at the effective scope. Use context.autoCompactThreshold, and put a provider model’s contextWindowSize inside its matching modelProviders entry.

Start with /status, /model, /doctor, /context detail, and /summary in the current session. Review the checkpoint file before choosing a compression command. Even if a summary is imperfect, you will still have traceable code and task state from which to recover.

Ready to optimize your LLM workflow?

Join thousands of developers building faster, smarter, and more cost-effective AI applications with BetterToken.

Get Started for Free