<span id="查看与恢复工作流历史"></span>

# Inspect and Restore Workflow History

Paginate candidate history within a workflow authoring conversation and restore a selected compiled candidate as a new proposal for review.

(sdk-ai-studio-workflow-history-flow)=
<span id="任务流程"></span>

## Task flow

1. Pass the conversation context ID (`WORKFLOW_CONTEXT_ID`) from the authoring task and paginate candidate history by authoring task.
2. Select a compiled candidate (`ok` is true) from the returned entries and record its source task ID and source artifact ID.
3. Submit a restoration request with a unique request identifier (`RESTORE_REQUEST_ID`) to obtain a new artifact ID, proposal ID, and reset test state.
4. Review and retest the restored proposal in the original conversation before accepting and publishing it.

(sdk-ai-studio-workflow-history-prepare)=
<span id="准备"></span>

## Prerequisites

1. Complete the endpoint, personal access token, and workspace setup in [Use the SDK](../../../quickstart/ai-studio/sdk.md).
2. **Conversation context ID** (`WORKFLOW_CONTEXT_ID`): retain the conversation context ID from the original workflow authoring task; history queries aggregate candidates by authoring conversation, whereas workflow IDs, standalone conversation record IDs, and execution IDs identify different resources.
3. **Restoration request ID** (`RESTORE_REQUEST_ID`): generate and save a unique idempotency identifier before calling restore; keep the same identifier and source selection when retrying after an uncertain network outcome, and generate a new identifier when selecting a different source candidate.

(sdk-ai-studio-workflow-history-list)=
<span id="按任务分页读取历史"></span>

## Read history with task-based pagination

The example below reads up to 10 pages, requesting 20 authoring tasks per page. A single authoring task may produce multiple candidate entries or zero visible entries; advance pagination using the returned task total (`total_tasks`) and page size (`limit`), stopping once the offset reaches or exceeds `total_tasks`.

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
import os

import moi_product_sdk as sdk

client = sdk.new_with_personal_access_token(
    os.environ["PRODUCT_API_BASE_URL"], os.environ["PRODUCT_API_KEY"]
)
workflows = client.workspace(os.environ["WORKSPACE_ID"]).workflows()
context_id = os.environ["WORKFLOW_CONTEXT_ID"]
entries = []
offset = 0
for _ in range(10):
    page = workflows.history(context_id, 20, offset)
    entries.extend(page.items)
    for entry in page.items:
        print(entry.candidate_ref.task_id, entry.candidate_ref.artifact_id,
              entry.status, entry.candidate.test_status, entry.created_at)
    offset += page.limit
    if offset >= page.total_tasks:
        break
    if page.limit <= 0:
        raise RuntimeError("Invalid task pagination")
else:
    raise RuntimeError("History page budget reached; continue at the returned task offset")
print("Candidate entries:", len(entries), "Task offset:", offset)
```

::::

::::{tab-item} Go
:sync: go

```go
package main

import (
	"context"
	"fmt"
	"os"

	sdk "github.com/matrixorigin/matrixflow/sdk/go-sdk"
)

func main() {
	ctx := context.Background()
	client, err := sdk.NewWithPersonalAccessToken(
		os.Getenv("PRODUCT_API_BASE_URL"),
		os.Getenv("PRODUCT_API_KEY"),
	)
	if err != nil {
		panic(err)
	}
	defer client.Close()
	workspace, err := client.Workspace(os.Getenv("WORKSPACE_ID"))
	if err != nil {
		panic(err)
	}
	workflows := workspace.Workflows()
	contextID := os.Getenv("WORKFLOW_CONTEXT_ID")
	var entries []*sdk.WorkflowHistoryEntry
	offset, complete := 0, false
	for pageIndex := 0; pageIndex < 10; pageIndex++ {
		page, err := workflows.History(ctx, contextID, 20, offset)
		if err != nil {
			panic(err)
		}
		entries = append(entries, page.GetItems()...)
		for _, entry := range page.GetItems() {
			fmt.Println(entry.GetCandidateRef().GetTaskId(), entry.GetCandidateRef().GetArtifactId(),
				entry.GetStatus(), entry.GetCandidate().GetTestStatus(), entry.GetCreatedAt())
		}
		offset += int(page.GetLimit())
		if offset >= int(page.GetTotalTasks()) {
			complete = true
			break
		}
		if page.GetLimit() <= 0 {
			panic("Invalid task pagination")
		}
	}
	if !complete {
		panic("History page budget reached; continue at the returned task offset")
	}
	fmt.Println("Candidate entries:", len(entries), "Task offset:", offset)
}
```

::::

:::::

(sdk-ai-studio-workflow-history-restore)=
<span id="恢复选中的历史方案"></span>

## Restore a selected historical candidate

Select a compiled candidate from the history entries collected above (uncompiled source snapshots cannot be restored) and pass its source task ID (`RESTORE_TASK_ID`) and source artifact ID (`RESTORE_ARTIFACT_ID`). Restoration creates a new pending proposal under the source task and returns a new `artifact_id`, a new confirmation proposal ID, and a reset test status; subsequent testing and acceptance must use the newly returned `artifact_id` and proposal ID.

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
source_task = os.environ["RESTORE_TASK_ID"]
source_artifact = os.environ["RESTORE_ARTIFACT_ID"]
selected = next((entry for entry in entries
                 if entry.candidate_ref.task_id == source_task
                 and entry.candidate_ref.artifact_id == source_artifact
                 and entry.candidate.ok), None)
if selected is None:
    raise RuntimeError("Choose a compiled candidate from the history page")
restored = workflows.restore_history(sdk.WorkflowHistoryRestoreRequest(
    context_id=context_id, request_id=os.environ["RESTORE_REQUEST_ID"],
    candidate_ref=sdk.WorkflowCandidateRef(source_task, source_artifact),
))
print("Restored reference:", restored.candidate_ref.task_id, restored.candidate_ref.artifact_id)
print("Proposal:", restored.candidate.proposal_id, "State:", restored.status,
      "Tests:", restored.candidate.test_status)
```

::::

::::{tab-item} Go
:sync: go

```go
sourceTask, sourceArtifact := os.Getenv("RESTORE_TASK_ID"), os.Getenv("RESTORE_ARTIFACT_ID")
found := false
for _, entry := range entries {
	if entry.GetCandidateRef().GetTaskId() == sourceTask &&
		entry.GetCandidateRef().GetArtifactId() == sourceArtifact &&
		entry.GetCandidate().GetOk() {
		found = true
	}
}
if !found {
	panic("Choose a compiled candidate from the history page")
}
restored, err := workflows.RestoreHistory(ctx, sdk.WorkflowHistoryRestoreRequest{
	ContextID:    contextID,
	RequestID:    os.Getenv("RESTORE_REQUEST_ID"),
	CandidateRef: sdk.WorkflowCandidateRef{TaskID: sourceTask, ArtifactID: sourceArtifact},
})
if err != nil {
	panic(err)
}
fmt.Println("Restored reference:", restored.GetCandidateRef().GetTaskId(), restored.GetCandidateRef().GetArtifactId())
fmt.Println("Proposal:", restored.GetCandidate().GetProposalId(), "State:", restored.GetStatus(), "Tests:", restored.GetCandidate().GetTestStatus())
```

::::

:::::

Restoration leaves the source candidate unchanged and does not automatically accept, publish, or overwrite the saved live workflow. The restored proposal starts with a fresh test state; review its configuration, rerun tests, and obtain approval in the original conversation before proceeding to [Confirm and Publish Workflow Proposals](确认并发布工作流方案.md#sdk-ai-studio-workflow-proposal-publish). Inspect `current` and `saved_workflow` separately when reading history responses (either field may be absent): an acceptance record indicates prior approval only, and a saved workflow version may predate that acceptance or originate from another conversation targeting the same workflow.

(sdk-ai-studio-workflow-history-next)=
<span id="下一步"></span>

## Next steps

- [Test and Submit Workflow Projects](测试并提交工作流项目.md#sdk-ai-studio-workflow-project-submit)
- [Confirm and Publish Workflow Proposals](确认并发布工作流方案.md#sdk-ai-studio-workflow-proposal-publish)
